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
|
|---|---|---|---|---|---|---|---|---|
41,771,725
|
Ansible 2.1.2 playbook pass SSH password and sudo password as command line args
|
I've looked around but couldn't find a proper solution, I want to run playbook for multiple users on multiple hosts and my roles use the user specific info such as name, email, id ... Now instead of running the playbook for each user I wrote a python script that invokes the ansible ansible-playbook -i hosts --ask-become-pass --ask-pass ./playbooks/myplaybook.yml But for the above command to work I want to pass SSH password and SUDO password as arguments to the command. I checked ansible-playbook documentation but was unable to find it. What would be the best way to achieve this?
|
Ansible 2.1.2 playbook pass SSH password and sudo password as command line args I've looked around but couldn't find a proper solution, I want to run playbook for multiple users on multiple hosts and my roles use the user specific info such as name, email, id ... Now instead of running the playbook for each user I wrote a python script that invokes the ansible ansible-playbook -i hosts --ask-become-pass --ask-pass ./playbooks/myplaybook.yml But for the above command to work I want to pass SSH password and SUDO password as arguments to the command. I checked ansible-playbook documentation but was unable to find it. What would be the best way to achieve this?
|
ansible
| 19
| 29,772
| 1
|
https://stackoverflow.com/questions/41771725/ansible-2-1-2-playbook-pass-ssh-password-and-sudo-password-as-command-line-args
|
32,783,852
|
Ansible best practice do not repeat common role
|
On the Ansible best practices page: [URL] it shows an example where the master playbook site.yml includes a couple of other top-level playbooks webservers.yml and dbservers.yml. Within those playbooks they each include the common role. Some inventory files I have all my groups run on one single host. Another inventory file I have a host per group. For the case where ever group is on one host, if I run site.yml you can see that the common role is getting played twice, one for webservers.yml and one for dbservers.yml. What is a solution to avoid this? I guess you can take out the common role from webservers.yml and dbservers.yml and instead within site.yml have a task that targets both with the common role. But then I can not individually provision a webserver or dbserver with common.
|
Ansible best practice do not repeat common role On the Ansible best practices page: [URL] it shows an example where the master playbook site.yml includes a couple of other top-level playbooks webservers.yml and dbservers.yml. Within those playbooks they each include the common role. Some inventory files I have all my groups run on one single host. Another inventory file I have a host per group. For the case where ever group is on one host, if I run site.yml you can see that the common role is getting played twice, one for webservers.yml and one for dbservers.yml. What is a solution to avoid this? I guess you can take out the common role from webservers.yml and dbservers.yml and instead within site.yml have a task that targets both with the common role. But then I can not individually provision a webserver or dbserver with common.
|
roles, ansible, organization
| 19
| 13,975
| 7
|
https://stackoverflow.com/questions/32783852/ansible-best-practice-do-not-repeat-common-role
|
20,074,736
|
Ansible: How to use variables defined in inventory file (hosts) in my playbook?
|
As the subject says. I have some host variables defined in my hosts inventory file. How do I access them in my playbook? Here is an example. Based on all my research I was expecting foo and bar to be part of hostvars . I can put host specific variables in separate var files, but I would love to keep them in my inventory file "attached" to a host. I don't want to use it in templates. ansible version: 1.3.2, ansible_distribution_version: 6.4 bash $ bash $ ansible --version ansible 1.3.2 bash $ bash $ cat test_inv.ini [foobar] someHost foo="some string" bar=123 someOtherHost foo="some other string" bar=456 bash $ bash $ cat test.yml --- - name: test variables... hosts: all vars: - some_junk: "1" # gather_facts: no # foo and bar are unavailable whether I gather facts or not. tasks: - debug: msg="hostvars={{hostvars}}" - debug: msg="vars={{vars}}" - debug: msg="groups={{groups}}" - debug: msg="some_junk={{some_junk}}" # - debug: msg="???? HOW DO I PRINT values of host specific variables foo and bar defined in inventory file ???" bash $ bash $ bash $ ansible-playbook -i test_inv.ini test.yml PLAY [test variables...] ****************************************************** GATHERING FACTS *************************************************************** ok: [someHost] TASK: [debug msg="hostvars={{hostvars}}"] ************************************* ok: [someHost] => {"msg": "hostvars={'someHost': {u'facter_operatingsystem': u'RedHat', u'facter_selinux_current_mode': u'enforcing', u'facter_hostname': u'someHost', 'module_setup': True, u'facter_memoryfree_mb': u'1792.70', u'ansible_distribution_version': u'6.4' // ...........snip...........// u'VMware IDE CDR10'}}"} TASK: [debug msg="vars={{vars}}"] ********************************************* ok: [someHost] => {"msg": "vars={'some_junk': '1', 'delegate_to': None, 'changed_when': None, 'register': None, 'inventory_dir': '/login/sg219898/PPP/automation/ansible', 'always_run': False, 'ignore_errors': False}"} TASK: [debug msg="groups={{groups}}"] ***************************************** ok: [someHost] => {"msg": "groups={'ungrouped': [], 'foobar': ['someHost'], 'all': ['someHost']}"} TASK: [debug msg="some_junk=1"] *********************************************** ok: [someHost] => {"msg": "some_junk=1"} PLAY RECAP ******************************************************************** someHost : ok=5 changed=0 unreachable=0 failed=0 bash $
|
Ansible: How to use variables defined in inventory file (hosts) in my playbook? As the subject says. I have some host variables defined in my hosts inventory file. How do I access them in my playbook? Here is an example. Based on all my research I was expecting foo and bar to be part of hostvars . I can put host specific variables in separate var files, but I would love to keep them in my inventory file "attached" to a host. I don't want to use it in templates. ansible version: 1.3.2, ansible_distribution_version: 6.4 bash $ bash $ ansible --version ansible 1.3.2 bash $ bash $ cat test_inv.ini [foobar] someHost foo="some string" bar=123 someOtherHost foo="some other string" bar=456 bash $ bash $ cat test.yml --- - name: test variables... hosts: all vars: - some_junk: "1" # gather_facts: no # foo and bar are unavailable whether I gather facts or not. tasks: - debug: msg="hostvars={{hostvars}}" - debug: msg="vars={{vars}}" - debug: msg="groups={{groups}}" - debug: msg="some_junk={{some_junk}}" # - debug: msg="???? HOW DO I PRINT values of host specific variables foo and bar defined in inventory file ???" bash $ bash $ bash $ ansible-playbook -i test_inv.ini test.yml PLAY [test variables...] ****************************************************** GATHERING FACTS *************************************************************** ok: [someHost] TASK: [debug msg="hostvars={{hostvars}}"] ************************************* ok: [someHost] => {"msg": "hostvars={'someHost': {u'facter_operatingsystem': u'RedHat', u'facter_selinux_current_mode': u'enforcing', u'facter_hostname': u'someHost', 'module_setup': True, u'facter_memoryfree_mb': u'1792.70', u'ansible_distribution_version': u'6.4' // ...........snip...........// u'VMware IDE CDR10'}}"} TASK: [debug msg="vars={{vars}}"] ********************************************* ok: [someHost] => {"msg": "vars={'some_junk': '1', 'delegate_to': None, 'changed_when': None, 'register': None, 'inventory_dir': '/login/sg219898/PPP/automation/ansible', 'always_run': False, 'ignore_errors': False}"} TASK: [debug msg="groups={{groups}}"] ***************************************** ok: [someHost] => {"msg": "groups={'ungrouped': [], 'foobar': ['someHost'], 'all': ['someHost']}"} TASK: [debug msg="some_junk=1"] *********************************************** ok: [someHost] => {"msg": "some_junk=1"} PLAY RECAP ******************************************************************** someHost : ok=5 changed=0 unreachable=0 failed=0 bash $
|
variables, ansible, ansible-inventory
| 19
| 33,129
| 1
|
https://stackoverflow.com/questions/20074736/ansible-how-to-use-variables-defined-in-inventory-file-hosts-in-my-playbook
|
45,152,074
|
What is the args section in an ansible command
|
This example only runs when /path/to/database doesn't exist: # You can also use the 'args' form to provide the options. - name: This command will change the working directory to somedir/ and will only run when /path/to/database doesn't exist. command: /usr/bin/make_database.sh arg1 arg2 args: chdir: somedir/ creates: /path/to/database but why is it listed under args: ? And what's the args: setting for?
|
What is the args section in an ansible command This example only runs when /path/to/database doesn't exist: # You can also use the 'args' form to provide the options. - name: This command will change the working directory to somedir/ and will only run when /path/to/database doesn't exist. command: /usr/bin/make_database.sh arg1 arg2 args: chdir: somedir/ creates: /path/to/database but why is it listed under args: ? And what's the args: setting for?
|
ansible
| 19
| 21,700
| 1
|
https://stackoverflow.com/questions/45152074/what-is-the-args-section-in-an-ansible-command
|
29,039,588
|
how to use lookup('file') in ansible when the file might not exist?
|
I want to lookup the contents of a file on the ansible control node -- example: - hosts: all vars: somevar: "{{ lookup('file', playbook_dir + '/some/path' + inventory_hostname) }}" if the file does not exist I'd like the variable to be undefined or set to a default value. The lookup module throws an error however if the file doesn't exist. What's the right way to handle this error so that I can branch on the existence of somevar within my code?
|
how to use lookup('file') in ansible when the file might not exist? I want to lookup the contents of a file on the ansible control node -- example: - hosts: all vars: somevar: "{{ lookup('file', playbook_dir + '/some/path' + inventory_hostname) }}" if the file does not exist I'd like the variable to be undefined or set to a default value. The lookup module throws an error however if the file doesn't exist. What's the right way to handle this error so that I can branch on the existence of somevar within my code?
|
ansible
| 19
| 16,981
| 3
|
https://stackoverflow.com/questions/29039588/how-to-use-lookupfile-in-ansible-when-the-file-might-not-exist
|
30,580,085
|
Accessing remote_user variable
|
This seems to work, but is it fragile? I want the owner and group in the files command to be set to someguy . I'd expect to be able to use {{ remote_user }} but that doesn't work. This is an example playbook showing what I mean. --- - hosts: foobar remote_user: someguy tasks: - name: configure /usr/src/foo file: dest: /usr/src/foo state: directory owner: {{ ansible_ssh_user }} group: {{ ansible_ssh_user }} recurse: yes sudo: yes This doesn't work: --- - hosts: foobar remote_user: someguy tasks: - name: configure /usr/src/foo file: dest: /usr/src/foo state: directory owner: {{ remote_user }} group: {{ remote_user }} recurse: yes sudo: yes One or more undefined variables: 'remote_user' is undefined
|
Accessing remote_user variable This seems to work, but is it fragile? I want the owner and group in the files command to be set to someguy . I'd expect to be able to use {{ remote_user }} but that doesn't work. This is an example playbook showing what I mean. --- - hosts: foobar remote_user: someguy tasks: - name: configure /usr/src/foo file: dest: /usr/src/foo state: directory owner: {{ ansible_ssh_user }} group: {{ ansible_ssh_user }} recurse: yes sudo: yes This doesn't work: --- - hosts: foobar remote_user: someguy tasks: - name: configure /usr/src/foo file: dest: /usr/src/foo state: directory owner: {{ remote_user }} group: {{ remote_user }} recurse: yes sudo: yes One or more undefined variables: 'remote_user' is undefined
|
ansible
| 19
| 11,865
| 4
|
https://stackoverflow.com/questions/30580085/accessing-remote-user-variable
|
36,958,125
|
Ansible roles/packages - Ansible Galaxy - error on installation MAC OSX
|
Im trying to install ansible-galaxy roles on Mac OS X El Capitan via CLI $ ansible-galaxy install -r requirements.yml I am getting this error: ERROR! Unexpected Exception: (setuptools 1.1.6 (/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), Requirement.parse('setuptools>=11.3')) the full traceback was: Traceback (most recent call last): File "/usr/local/bin/ansible-galaxy", line 73, in <module> mycli = getattr(__import__("ansible.cli.%s" % sub, fromlist=[myclass]), myclass) File "/Library/Python/2.7/site-packages/ansible/cli/galaxy.py", line 38, in <module> from ansible.galaxy.role import GalaxyRole File "/Library/Python/2.7/site-packages/ansible/galaxy/role.py", line 35, in <module> from ansible.playbook.role.requirement import RoleRequirement File "/Library/Python/2.7/site-packages/ansible/playbook/__init__.py", line 25, in <module> from ansible.playbook.play import Play File "/Library/Python/2.7/site-packages/ansible/playbook/play.py", line 27, in <module> from ansible.playbook.base import Base File "/Library/Python/2.7/site-packages/ansible/playbook/base.py", line 35, in <module> from ansible.parsing.dataloader import DataLoader File "/Library/Python/2.7/site-packages/ansible/parsing/dataloader.py", line 32, in <module> from ansible.parsing.vault import VaultLib File "/Library/Python/2.7/site-packages/ansible/parsing/vault/__init__.py", line 67, in <module> from cryptography.hazmat.primitives.hashes import SHA256 as c_SHA256 File "/Library/Python/2.7/site-packages/cryptography/hazmat/primitives/hashes.py", line 15, in <module> from cryptography.hazmat.backends.interfaces import HashBackend File "/Library/Python/2.7/site-packages/cryptography/hazmat/backends/__init__.py", line 7, in <module> import pkg_resources File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2797, in <module> parse_requirements(__requires__), Environment() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 580, in resolve raise VersionConflict(dist,req) # XXX put more info here VersionConflict: (setuptools 1.1.6 (/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), Requirement.parse('setuptools>=11.3'))
|
Ansible roles/packages - Ansible Galaxy - error on installation MAC OSX Im trying to install ansible-galaxy roles on Mac OS X El Capitan via CLI $ ansible-galaxy install -r requirements.yml I am getting this error: ERROR! Unexpected Exception: (setuptools 1.1.6 (/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), Requirement.parse('setuptools>=11.3')) the full traceback was: Traceback (most recent call last): File "/usr/local/bin/ansible-galaxy", line 73, in <module> mycli = getattr(__import__("ansible.cli.%s" % sub, fromlist=[myclass]), myclass) File "/Library/Python/2.7/site-packages/ansible/cli/galaxy.py", line 38, in <module> from ansible.galaxy.role import GalaxyRole File "/Library/Python/2.7/site-packages/ansible/galaxy/role.py", line 35, in <module> from ansible.playbook.role.requirement import RoleRequirement File "/Library/Python/2.7/site-packages/ansible/playbook/__init__.py", line 25, in <module> from ansible.playbook.play import Play File "/Library/Python/2.7/site-packages/ansible/playbook/play.py", line 27, in <module> from ansible.playbook.base import Base File "/Library/Python/2.7/site-packages/ansible/playbook/base.py", line 35, in <module> from ansible.parsing.dataloader import DataLoader File "/Library/Python/2.7/site-packages/ansible/parsing/dataloader.py", line 32, in <module> from ansible.parsing.vault import VaultLib File "/Library/Python/2.7/site-packages/ansible/parsing/vault/__init__.py", line 67, in <module> from cryptography.hazmat.primitives.hashes import SHA256 as c_SHA256 File "/Library/Python/2.7/site-packages/cryptography/hazmat/primitives/hashes.py", line 15, in <module> from cryptography.hazmat.backends.interfaces import HashBackend File "/Library/Python/2.7/site-packages/cryptography/hazmat/backends/__init__.py", line 7, in <module> import pkg_resources File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2797, in <module> parse_requirements(__requires__), Environment() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 580, in resolve raise VersionConflict(dist,req) # XXX put more info here VersionConflict: (setuptools 1.1.6 (/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python), Requirement.parse('setuptools>=11.3'))
|
python, ansible, ansible-galaxy
| 18
| 8,073
| 1
|
https://stackoverflow.com/questions/36958125/ansible-roles-packages-ansible-galaxy-error-on-installation-mac-osx
|
29,724,680
|
How do I use remote machine's SSH keys in ansible git module
|
I've been trying to get Ansible to provision a remote machine, and I want the remote machine to be set up with its own keys, and have the ability to clone git repositories from Bitbucket. The user is set up, has its own id_rsa.pub, and the key has been registered with bitbucket. But, when I use the Ansible Git module, it looks like the module always tries to use the keys from the machine running the playbook. How do I get the git module to use the id_rsa.pub from the remote machine? The relevant task is this: - name: be sure prom-king has an up-to-date clone of its own repository git: repo: "ssh://ddcrnd@bitbucket.org/prom-king.git" dest: /home/promking/prom-king accept_hostkey: yes clone: yes key_file: /home/promking/.ssh/id_rsa.pub update: yes The relevant inventory is this # inventory file for use with the vagrant box in the testing directory. [prom-king] 192.168.168.192 ansible_ssh_host=127.0.0.1 ansible_sudo=true ansible_connection=ssh ansible_ssh_port=2222 ansible_ssh_user=vagrant ansible_ssh_private_key_file=testing/.vagrant/machines/default/virtualbox/private_key
|
How do I use remote machine's SSH keys in ansible git module I've been trying to get Ansible to provision a remote machine, and I want the remote machine to be set up with its own keys, and have the ability to clone git repositories from Bitbucket. The user is set up, has its own id_rsa.pub, and the key has been registered with bitbucket. But, when I use the Ansible Git module, it looks like the module always tries to use the keys from the machine running the playbook. How do I get the git module to use the id_rsa.pub from the remote machine? The relevant task is this: - name: be sure prom-king has an up-to-date clone of its own repository git: repo: "ssh://ddcrnd@bitbucket.org/prom-king.git" dest: /home/promking/prom-king accept_hostkey: yes clone: yes key_file: /home/promking/.ssh/id_rsa.pub update: yes The relevant inventory is this # inventory file for use with the vagrant box in the testing directory. [prom-king] 192.168.168.192 ansible_ssh_host=127.0.0.1 ansible_sudo=true ansible_connection=ssh ansible_ssh_port=2222 ansible_ssh_user=vagrant ansible_ssh_private_key_file=testing/.vagrant/machines/default/virtualbox/private_key
|
git, ssh, ssh-keys, ansible
| 18
| 41,051
| 3
|
https://stackoverflow.com/questions/29724680/how-do-i-use-remote-machines-ssh-keys-in-ansible-git-module
|
25,136,498
|
ansible answers to mysql_secure_installation
|
I can't realize how to write a task, that answers mysql_secure_installation script questions. I only have shell: mysql_secure_installation <<< '1111' executable=/bin/bash and no ideas on how to continue answering. What would be the best way to solve this? Thanks in advance!
|
ansible answers to mysql_secure_installation I can't realize how to write a task, that answers mysql_secure_installation script questions. I only have shell: mysql_secure_installation <<< '1111' executable=/bin/bash and no ideas on how to continue answering. What would be the best way to solve this? Thanks in advance!
|
bash, ansible
| 18
| 23,230
| 3
|
https://stackoverflow.com/questions/25136498/ansible-answers-to-mysql-secure-installation
|
63,534,262
|
How to fix following ansible galaxy SSL error?
|
Started learning Ansible and want to facilitate ansible-galaxy search nginx command, but I'm getting: ERROR! Unknown error when attempting to call Galaxy at '[URL] <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> Had try to use ansible-galaxy --ignore-certs search nginx and ansible-galaxy -c search nginx but now getting ansible-galaxy: error: unrecognized arguments: --ignore-certs for booth. OS : Distributor ID: Ubuntu Description: Ubuntu 18.04.5 LTS Release: 18.04 Codename: bionic Ansible version: ansible 2.9.5 config file = /home/maciej/projects/priv/ansible_nauka/packt_course/ansible.cfg configured module search path = ['/home/maciej/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/maciej/.local/lib/python3.6/site-packages/ansible executable location = /home/maciej/.local/bin/ansible python version = 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0]
|
How to fix following ansible galaxy SSL error? Started learning Ansible and want to facilitate ansible-galaxy search nginx command, but I'm getting: ERROR! Unknown error when attempting to call Galaxy at '[URL] <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> Had try to use ansible-galaxy --ignore-certs search nginx and ansible-galaxy -c search nginx but now getting ansible-galaxy: error: unrecognized arguments: --ignore-certs for booth. OS : Distributor ID: Ubuntu Description: Ubuntu 18.04.5 LTS Release: 18.04 Codename: bionic Ansible version: ansible 2.9.5 config file = /home/maciej/projects/priv/ansible_nauka/packt_course/ansible.cfg configured module search path = ['/home/maciej/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /home/maciej/.local/lib/python3.6/site-packages/ansible executable location = /home/maciej/.local/bin/ansible python version = 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0]
|
ssl, ansible, ubuntu-18.04, ansible-galaxy
| 18
| 67,197
| 7
|
https://stackoverflow.com/questions/63534262/how-to-fix-following-ansible-galaxy-ssl-error
|
32,103,081
|
Run a PostgreSQL script using Ansible
|
I am looking for a way to run a Postgres script using Ansible. While I found a reasonably good example Here , I need to: Run the script as user postgres I don't necessarily need to keep a copy of the script on the server so if I need to have a copy, it will only be for temp use. Can anyone tell me if this is possible and if so an example of running it. Here is what I tried so far using Ansible and it just hung at these points: - name: Testing DB to make sure it is available command: psql -U bob image register: b - debug: b - name: Verifying Tables exist in Image shell: \d image register: c - debug: c - name: Exiting Image DB shell: \q register: d - debug: d - name: Going to Agent DB command: psql -U bob agent register: e - debug: e This always hangs at the first part of it when logging into the image DB.
|
Run a PostgreSQL script using Ansible I am looking for a way to run a Postgres script using Ansible. While I found a reasonably good example Here , I need to: Run the script as user postgres I don't necessarily need to keep a copy of the script on the server so if I need to have a copy, it will only be for temp use. Can anyone tell me if this is possible and if so an example of running it. Here is what I tried so far using Ansible and it just hung at these points: - name: Testing DB to make sure it is available command: psql -U bob image register: b - debug: b - name: Verifying Tables exist in Image shell: \d image register: c - debug: c - name: Exiting Image DB shell: \q register: d - debug: d - name: Going to Agent DB command: psql -U bob agent register: e - debug: e This always hangs at the first part of it when logging into the image DB.
|
postgresql, ansible
| 18
| 38,238
| 3
|
https://stackoverflow.com/questions/32103081/run-a-postgresql-script-using-ansible
|
42,001,251
|
Ansible uncomment line in file
|
I want to uncomment a line in file sshd_config by using Ansible and I have the following working configuration: - name: Uncomment line from /etc/ssh/sshd_config lineinfile: dest: /etc/ssh/sshd_config regexp: '^#AuthorizedKeysFile' line: 'AuthorizedKeysFile .ssh/authorized_keys' However this config only works if the line starts by #AuthorizedKeysFile , but it won't work if the line starts by # AuthorizedKeysFile or # AuthorizedKeysFile (spaces between # and the words). How can I configure the regexp so it won't take into account any number of spaces after '#'? I've tried to add another lineinfile option with a space after '#', but this is not a good solution: - name: Uncomment line from /etc/ssh/sshd_config lineinfile: dest: /etc/ssh/sshd_config regexp: '# AuthorizedKeysFile' line: 'AuthorizedKeysFile .ssh/authorized_keys'
|
Ansible uncomment line in file I want to uncomment a line in file sshd_config by using Ansible and I have the following working configuration: - name: Uncomment line from /etc/ssh/sshd_config lineinfile: dest: /etc/ssh/sshd_config regexp: '^#AuthorizedKeysFile' line: 'AuthorizedKeysFile .ssh/authorized_keys' However this config only works if the line starts by #AuthorizedKeysFile , but it won't work if the line starts by # AuthorizedKeysFile or # AuthorizedKeysFile (spaces between # and the words). How can I configure the regexp so it won't take into account any number of spaces after '#'? I've tried to add another lineinfile option with a space after '#', but this is not a good solution: - name: Uncomment line from /etc/ssh/sshd_config lineinfile: dest: /etc/ssh/sshd_config regexp: '# AuthorizedKeysFile' line: 'AuthorizedKeysFile .ssh/authorized_keys'
|
linux, ansible
| 18
| 21,232
| 5
|
https://stackoverflow.com/questions/42001251/ansible-uncomment-line-in-file
|
40,927,792
|
Ansible - how to remove an item from a list?
|
I'd like to remove an item from a list, based on another list. "my_list_one": [ "item1", "item2", "item3" ] My second list: "my_list_two": [ "item3" ] How do I remove 'item3' from this list, to set a new fact? I tried using '-' and union, but this does not end in the desired end result. set_fact: my_list_one: "{{ my_list_one | union(my_list_two) }}" End goal: "my_list_one": [ "item1", "item2" ]
|
Ansible - how to remove an item from a list? I'd like to remove an item from a list, based on another list. "my_list_one": [ "item1", "item2", "item3" ] My second list: "my_list_two": [ "item3" ] How do I remove 'item3' from this list, to set a new fact? I tried using '-' and union, but this does not end in the desired end result. set_fact: my_list_one: "{{ my_list_one | union(my_list_two) }}" End goal: "my_list_one": [ "item1", "item2" ]
|
python, ansible, jinja2
| 18
| 62,518
| 2
|
https://stackoverflow.com/questions/40927792/ansible-how-to-remove-an-item-from-a-list
|
35,662,388
|
ansible with_items list of lists is flattening
|
I'm trying to use ansible to loop over a list of lists to install some packages. But {{item}} is returning every element in the sub lists rather than the sublist itself. I have a yaml file which come from a manifest list from outside ansible and it looks like this: --- modules: - ['module','version','extra'] - ['module2','version','extra'] - ['module3','version','extra'] My task looks like this: task: - include_vars: /path/to/external/file.yml - name: install modules yum: name={{item.0}} state=installed with_items: "{{ modules }}" When I run that I get: fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! int object has no element 0"} When I try: - debug: msg="{{item}}" with_items: "{{module}}" it prints every element (module, version, extra, and so on), not just the sublist (which is what I would expect)
|
ansible with_items list of lists is flattening I'm trying to use ansible to loop over a list of lists to install some packages. But {{item}} is returning every element in the sub lists rather than the sublist itself. I have a yaml file which come from a manifest list from outside ansible and it looks like this: --- modules: - ['module','version','extra'] - ['module2','version','extra'] - ['module3','version','extra'] My task looks like this: task: - include_vars: /path/to/external/file.yml - name: install modules yum: name={{item.0}} state=installed with_items: "{{ modules }}" When I run that I get: fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! int object has no element 0"} When I try: - debug: msg="{{item}}" with_items: "{{module}}" it prints every element (module, version, extra, and so on), not just the sublist (which is what I would expect)
|
yaml, ansible
| 18
| 58,818
| 4
|
https://stackoverflow.com/questions/35662388/ansible-with-items-list-of-lists-is-flattening
|
62,182,998
|
How do you notify a handler in Ansible based solely on a conditional?
|
I would like to notify a handler in my role by doing something like this: - name: Notify handler notify: my_handler when: this_thing_is_true|bool But Ansible just whines: ERROR! no module/action detected in task. I have tried various wedges, such as: - name: Notify handler meta: noop notify: my_handler when: this_thing_is_true|bool But that similarly whines: [WARNING]: noop task does not support when conditional Any suggestions?
|
How do you notify a handler in Ansible based solely on a conditional? I would like to notify a handler in my role by doing something like this: - name: Notify handler notify: my_handler when: this_thing_is_true|bool But Ansible just whines: ERROR! no module/action detected in task. I have tried various wedges, such as: - name: Notify handler meta: noop notify: my_handler when: this_thing_is_true|bool But that similarly whines: [WARNING]: noop task does not support when conditional Any suggestions?
|
ansible, conditional-statements, notify
| 18
| 20,193
| 3
|
https://stackoverflow.com/questions/62182998/how-do-you-notify-a-handler-in-ansible-based-solely-on-a-conditional
|
50,440,515
|
Ansible error on shell command returning zero
|
Ansible doesn't seem to be able to handle the result '0' for shell commands. This - name: Check if swap exists shell: "swapon -s | grep -ci dev" register: swap_exists Returns an error "msg": "non-zero return code" But when I replace "dev" with "type", which actually always occurs and gives a count of at least 1, then the command is successful and no error is thrown. I also tried with command: instead of shell: - it doesn't give an error, but then the command is also not executed.
|
Ansible error on shell command returning zero Ansible doesn't seem to be able to handle the result '0' for shell commands. This - name: Check if swap exists shell: "swapon -s | grep -ci dev" register: swap_exists Returns an error "msg": "non-zero return code" But when I replace "dev" with "type", which actually always occurs and gives a count of at least 1, then the command is successful and no error is thrown. I also tried with command: instead of shell: - it doesn't give an error, but then the command is also not executed.
|
ansible
| 18
| 62,154
| 3
|
https://stackoverflow.com/questions/50440515/ansible-error-on-shell-command-returning-zero
|
25,694,249
|
ansible: using with_items with notify handler
|
I want to pass a variable to a notification handler, but can't find anywhere be it here on SO, the docs or the issues in the github repo, how to do it. What I'm doing is deploying multiple webapps, and when the code for one of those webapps is changed, it should restart the service for that webapp. From this SO question , I got this to work, somewhat: - hosts: localhost tasks: - name: "task 1" shell: "echo {{ item }}" register: "task_1_output" with_items: [a,b] - name: "task 2" debug: msg: "{{ item.item }}" when: item.changed with_items: task_1_output.results (Put it in test.yml and run it with ansible-playbook test.yml -c local .) But this registers the result of the first task and conditionally loops over that in the second task. My problem is that it gets messy when you have two or more tasks that need to notify the second task! For example, restart the web service if either the code was updated or the configuration was changed. AFAICT, there's no way to pass a variable to a handler. That would cleanly fix it for me. I found some issues on github where other people run into the same problem, and some syntaxes are proposed, but none of them actually work. Including a sub-playbook won't work either, because using with_items together with include was deprecated. In my playbooks, I have a site.yml that lists the roles of a group, then in the group_vars for that group I define the list of webapps (including the versions) that should be installed. This seems correct to me, because this way I can use the same playbook for staging and production. But maybe the only solution is to define the role multiple times, and duplicate the list of roles for staging and production. So what is the wisdom here?
|
ansible: using with_items with notify handler I want to pass a variable to a notification handler, but can't find anywhere be it here on SO, the docs or the issues in the github repo, how to do it. What I'm doing is deploying multiple webapps, and when the code for one of those webapps is changed, it should restart the service for that webapp. From this SO question , I got this to work, somewhat: - hosts: localhost tasks: - name: "task 1" shell: "echo {{ item }}" register: "task_1_output" with_items: [a,b] - name: "task 2" debug: msg: "{{ item.item }}" when: item.changed with_items: task_1_output.results (Put it in test.yml and run it with ansible-playbook test.yml -c local .) But this registers the result of the first task and conditionally loops over that in the second task. My problem is that it gets messy when you have two or more tasks that need to notify the second task! For example, restart the web service if either the code was updated or the configuration was changed. AFAICT, there's no way to pass a variable to a handler. That would cleanly fix it for me. I found some issues on github where other people run into the same problem, and some syntaxes are proposed, but none of them actually work. Including a sub-playbook won't work either, because using with_items together with include was deprecated. In my playbooks, I have a site.yml that lists the roles of a group, then in the group_vars for that group I define the list of webapps (including the versions) that should be installed. This seems correct to me, because this way I can use the same playbook for staging and production. But maybe the only solution is to define the role multiple times, and duplicate the list of roles for staging and production. So what is the wisdom here?
|
ansible
| 18
| 42,606
| 5
|
https://stackoverflow.com/questions/25694249/ansible-using-with-items-with-notify-handler
|
27,038,553
|
Ansible set_fact doesn't change the variable value
|
Scenario ansible-playbook is called with passed in extra var: -e my_var=init_value Then in a role code the value is supposed to change via set_fact call (variable other_var value is "new_value"): set_fact: my_var: {{ other_var }} This results in a nice output supposedly confirming alteration: {"ansible facts": {"my_var": "new_value"}} However echoing the variable after changing it shows the old value: echo {{ my_var }} -> "echo init_value" To add to that, when I set two variables in the above example: set_fact: my_var: {{ other_var }} set_fact: new_var: {{ other_var }} The new_var is set properly. Is the variable in some way immutable? How to use the set_fact to update the variable's value?
|
Ansible set_fact doesn't change the variable value Scenario ansible-playbook is called with passed in extra var: -e my_var=init_value Then in a role code the value is supposed to change via set_fact call (variable other_var value is "new_value"): set_fact: my_var: {{ other_var }} This results in a nice output supposedly confirming alteration: {"ansible facts": {"my_var": "new_value"}} However echoing the variable after changing it shows the old value: echo {{ my_var }} -> "echo init_value" To add to that, when I set two variables in the above example: set_fact: my_var: {{ other_var }} set_fact: new_var: {{ other_var }} The new_var is set properly. Is the variable in some way immutable? How to use the set_fact to update the variable's value?
|
shell, ansible
| 18
| 31,153
| 2
|
https://stackoverflow.com/questions/27038553/ansible-set-fact-doesnt-change-the-variable-value
|
40,696,130
|
How to remove or exclude an item in an Ansible template list?
|
I'm writing an Ansible template that needs to produce a list of ip's in a host group, excluding the current hosts IP. I've searched around online and through the documentation but I could not find any filters that allow you to remove an item in a list. I have created the (hacky) for loop below to do this but was wondering if anyone knew a "best practice" way of filtering like this. {% set filtered_list = [] %} {% for host in groups['my_group'] if host != ansible_host %} {{ filtered_list.append(host)}} {% endfor %} Lets say groups['my_group'] has 3 ip's (192.168.1.1, 192.168.1.2 and 192.168.1.3). When the template is generated for 192.168.1.1 it should only print the ip's 192.168.1.2 and 192.168.1.3.
|
How to remove or exclude an item in an Ansible template list? I'm writing an Ansible template that needs to produce a list of ip's in a host group, excluding the current hosts IP. I've searched around online and through the documentation but I could not find any filters that allow you to remove an item in a list. I have created the (hacky) for loop below to do this but was wondering if anyone knew a "best practice" way of filtering like this. {% set filtered_list = [] %} {% for host in groups['my_group'] if host != ansible_host %} {{ filtered_list.append(host)}} {% endfor %} Lets say groups['my_group'] has 3 ip's (192.168.1.1, 192.168.1.2 and 192.168.1.3). When the template is generated for 192.168.1.1 it should only print the ip's 192.168.1.2 and 192.168.1.3.
|
ansible, jinja2, ansible-template
| 18
| 23,542
| 1
|
https://stackoverflow.com/questions/40696130/how-to-remove-or-exclude-an-item-in-an-ansible-template-list
|
26,409,164
|
ansible ignore the run_once configuration on task
|
I am using Ansible and I want to run a task only once. I follow the documentation about how to configure and run a task only once - name: apt update shell: apt-get update run_once: true But when I run Ansible, it always runs this task. How can I run my task only once.
|
ansible ignore the run_once configuration on task I am using Ansible and I want to run a task only once. I follow the documentation about how to configure and run a task only once - name: apt update shell: apt-get update run_once: true But when I run Ansible, it always runs this task. How can I run my task only once.
|
task, ansible, idempotent
| 18
| 13,359
| 1
|
https://stackoverflow.com/questions/26409164/ansible-ignore-the-run-once-configuration-on-task
|
61,255,461
|
Ansible - check variable type
|
Apparently, according to several hours of searching nobody has encountered this use-case: Its simple - I would like to execute some ansible logic depending on variable type. Basically equivalent of e.g. instanceof(dict, var_name) but in Ansible: - name: test debug: msg: "{{ instanceof(var_name, dict) | ternary('is a dictionary', 'is something else') }}" Is there any way this can be done?
|
Ansible - check variable type Apparently, according to several hours of searching nobody has encountered this use-case: Its simple - I would like to execute some ansible logic depending on variable type. Basically equivalent of e.g. instanceof(dict, var_name) but in Ansible: - name: test debug: msg: "{{ instanceof(var_name, dict) | ternary('is a dictionary', 'is something else') }}" Is there any way this can be done?
|
ansible, jinja2
| 18
| 45,649
| 3
|
https://stackoverflow.com/questions/61255461/ansible-check-variable-type
|
40,290,837
|
Ansible create postgresql user with access to all tables?
|
This should be very simple. I want to make an Ansible statement to create a Postgres user that has connection privileges to a specific database and select/insert/update/delete privileges to all tables within that specific database. I tried the following: - name: Create postgres user for my app become: yes become_user: postgres postgresql_user: db: "mydatabase" name: "myappuser" password: "supersecretpassword" priv: CONNECT/ALL:SELECT,INSERT,UPDATE,DELETE I get relation \"ALL\" does not exist If I remove ALL: , I get Invalid privs specified for database: INSERT UPDATE SELECT DELETE
|
Ansible create postgresql user with access to all tables? This should be very simple. I want to make an Ansible statement to create a Postgres user that has connection privileges to a specific database and select/insert/update/delete privileges to all tables within that specific database. I tried the following: - name: Create postgres user for my app become: yes become_user: postgres postgresql_user: db: "mydatabase" name: "myappuser" password: "supersecretpassword" priv: CONNECT/ALL:SELECT,INSERT,UPDATE,DELETE I get relation \"ALL\" does not exist If I remove ALL: , I get Invalid privs specified for database: INSERT UPDATE SELECT DELETE
|
postgresql, ansible
| 18
| 22,078
| 3
|
https://stackoverflow.com/questions/40290837/ansible-create-postgresql-user-with-access-to-all-tables
|
33,255,249
|
How to delete a cron job with Ansible?
|
I have about 50 Debian Linux servers with a bad cron job: 0 * * * * ntpdate 10.20.0.1 I want to configure ntp sync with ntpd and so I need to delete this cron job. For configuring I use Ansible. I have tried to delete the cron entry with this play: tasks: - cron: name="ntpdate" minute="0" job="ntpdate 10.20.0.1" state=absent user="root" Nothing happened. Then I run this play: tasks: - cron: name="ntpdate" minute="0" job="ntpdate pool.ntp.org" state=present I see new cron job in output of "crontab -l": ... # m h dom mon dow command 0 * * * * ntpdate 10.20.0.1 #Ansible: ntpdate 0 * * * * ntpdate pool.ntp.org but /etc/cron.d is empty! I don't understand how the Ansible cron module works. How can I delete my manually configured cron job with Ansible's cron module?
|
How to delete a cron job with Ansible? I have about 50 Debian Linux servers with a bad cron job: 0 * * * * ntpdate 10.20.0.1 I want to configure ntp sync with ntpd and so I need to delete this cron job. For configuring I use Ansible. I have tried to delete the cron entry with this play: tasks: - cron: name="ntpdate" minute="0" job="ntpdate 10.20.0.1" state=absent user="root" Nothing happened. Then I run this play: tasks: - cron: name="ntpdate" minute="0" job="ntpdate pool.ntp.org" state=present I see new cron job in output of "crontab -l": ... # m h dom mon dow command 0 * * * * ntpdate 10.20.0.1 #Ansible: ntpdate 0 * * * * ntpdate pool.ntp.org but /etc/cron.d is empty! I don't understand how the Ansible cron module works. How can I delete my manually configured cron job with Ansible's cron module?
|
linux, debian, ansible
| 18
| 27,496
| 3
|
https://stackoverflow.com/questions/33255249/how-to-delete-a-cron-job-with-ansible
|
31,352,169
|
Ansible template - Destination directory does not exist error
|
I am new to ansible and I am using a template statement in my playbook to copy a file from my local machine to a remote machine. I get an error saying the destination directory does not exist, but it is there very much. I am using Centos 6.5 version (both my local and remote). Any help is appreciated.
|
Ansible template - Destination directory does not exist error I am new to ansible and I am using a template statement in my playbook to copy a file from my local machine to a remote machine. I get an error saying the destination directory does not exist, but it is there very much. I am using Centos 6.5 version (both my local and remote). Any help is appreciated.
|
templates, copy, ansible
| 18
| 42,010
| 1
|
https://stackoverflow.com/questions/31352169/ansible-template-destination-directory-does-not-exist-error
|
27,796,110
|
Is there some Ansible equivalent to "failed_when" for success
|
Looking at the documentation about error handling Ansible error handling I only see a way to fail the provisioning failed_when , I am wondering if there is any way to do the opposite. Something that looks like this: - name: ping pong redis command: redis-cli ping register: command_result success_when: "'PONG' in command_result.stderr" Thanks.
|
Is there some Ansible equivalent to "failed_when" for success Looking at the documentation about error handling Ansible error handling I only see a way to fail the provisioning failed_when , I am wondering if there is any way to do the opposite. Something that looks like this: - name: ping pong redis command: redis-cli ping register: command_result success_when: "'PONG' in command_result.stderr" Thanks.
|
linux, ansible
| 18
| 19,467
| 2
|
https://stackoverflow.com/questions/27796110/is-there-some-ansible-equivalent-to-failed-when-for-success
|
27,307,773
|
Set remote_user for set of tasks in Ansible playbook without repeating it per task
|
I am creating a playbook which first creates a new username. I then want to run "moretasks.yml" as that new user that I just created. Currently, I'm setting remote_user for every task. Is there a way I can set it for the entire set of tasks once? I couldn't seem to find examples of this, nor did any of my attempts to move remote_user around help. Below is main.yml: --- - name: Configure Instance(s) hosts: all remote_user: root gather_facts: true tags: - config - configure tasks: - include: createuser.yml new_user=username - include: moretasks.yml new_user=username - include: roottasks.yml #some tasks unrelated to username. moretasks.yml: --- - name: Task1 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" - name: Task2 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}"
|
Set remote_user for set of tasks in Ansible playbook without repeating it per task I am creating a playbook which first creates a new username. I then want to run "moretasks.yml" as that new user that I just created. Currently, I'm setting remote_user for every task. Is there a way I can set it for the entire set of tasks once? I couldn't seem to find examples of this, nor did any of my attempts to move remote_user around help. Below is main.yml: --- - name: Configure Instance(s) hosts: all remote_user: root gather_facts: true tags: - config - configure tasks: - include: createuser.yml new_user=username - include: moretasks.yml new_user=username - include: roottasks.yml #some tasks unrelated to username. moretasks.yml: --- - name: Task1 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}" - name: Task2 copy: src: /vagrant/FILE dest: ~/FILE remote_user: "{{newuser}}"
|
ansible
| 18
| 47,080
| 3
|
https://stackoverflow.com/questions/27307773/set-remote-user-for-set-of-tasks-in-ansible-playbook-without-repeating-it-per-ta
|
43,260,832
|
Increase timeout of SSH command in Ansible
|
I am currently using Ansible to provision bare metal using an IPv6 link local address. Once the servers are provisioned, ansible will run a series of tests on the server, as one shell command, to ensure provisioning was successful. These tests take approximately 10 minutes to run. The issue that I'm facing is that the connection seems to timeout before the command completes. Here is the error from Ansible: fatal: [fe80::5054:ff:XXXX:XXXX%eth0]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to fe80::5054:ff:XXXX:XXXX%eth0 closed.\r\n", "unreachable": true } By looking at this error, one might think there is an issue with the SSH connection. The SSH connection itself is good since several other tasks run successfully on the same host prior to this task. How can I increase the timeout so that Ansible will wait for the command to finish? Can this timeout be increased within the Ansible configuration, or do I need to modify the command itself to increase the timeout?
|
Increase timeout of SSH command in Ansible I am currently using Ansible to provision bare metal using an IPv6 link local address. Once the servers are provisioned, ansible will run a series of tests on the server, as one shell command, to ensure provisioning was successful. These tests take approximately 10 minutes to run. The issue that I'm facing is that the connection seems to timeout before the command completes. Here is the error from Ansible: fatal: [fe80::5054:ff:XXXX:XXXX%eth0]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to fe80::5054:ff:XXXX:XXXX%eth0 closed.\r\n", "unreachable": true } By looking at this error, one might think there is an issue with the SSH connection. The SSH connection itself is good since several other tasks run successfully on the same host prior to this task. How can I increase the timeout so that Ansible will wait for the command to finish? Can this timeout be increased within the Ansible configuration, or do I need to modify the command itself to increase the timeout?
|
ssh, ansible
| 18
| 65,940
| 3
|
https://stackoverflow.com/questions/43260832/increase-timeout-of-ssh-command-in-ansible
|
59,003,007
|
Install Ansible collections directly from a git URI with ansible-galaxy
|
The documentation for ansible-galaxy indicates the following: The ansible-galaxy command comes bundled with Ansible, and you can use it to install roles from Galaxy or directly from a git based SCM. You can also use it to create a new role, remove roles, or perform tasks on the Galaxy website. I'm trying to figure out how it's possible to install an Ansible collection " directly from a git based SCM " as indicated. When I run ansible-galaxy collections --help , from Ansible 2.9.1 on MacOS Catalina, I see the following: usage: ansible-galaxy collection install [-h] [-s API_SERVER] [--api-key API_KEY] [-c] [-v] [-f] [-i] [-n | --force-with-deps] [-p COLLECTIONS_PATH] [-r REQUIREMENTS] [collection_name [collection_name ...]] positional arguments: collection_name The collection(s) name or path/url to a tar.gz collection artifact. This is mutually exclusive with --requirements-file. optional arguments: -h, --help show this help message and exit -s API_SERVER, --server API_SERVER The Galaxy API server URL --api-key API_KEY The Ansible Galaxy API key which can be found at [URL] You can also use ansible-galaxy login to retrieve this key or set the token for the GALAXY_SERVER_LIST entry. -c, --ignore-certs Ignore SSL certificate validation errors. -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) -f, --force Force overwriting an existing role or collection -i, --ignore-errors Ignore errors during installation and continue with the next specified collection. This will not ignore dependency conflict errors. -n, --no-deps Don't download collections listed as dependencies. --force-with-deps Force overwriting an existing collection and its dependencies. -p COLLECTIONS_PATH, --collections-path COLLECTIONS_PATH The path to the directory containing your collections. -r REQUIREMENTS, --requirements-file REQUIREMENTS A file containing a list of collections to be installed. I tried specifying a GitHub repository URI for the -p parameter, but instead of recognizing a valid URI, ansible-galaxy tried to look in a subfolder named the URI that I specified. ansible-galaxy collection install -p [URL] trevor.trevormacos My expectation would be that specifying a GitHub repository URI for the -p parameter should properly indicate that I want to install a collection from that GitHub repository . Question : How do I instruct ansible-galaxy to install an Ansible collection directly from a GitHub URI ?
|
Install Ansible collections directly from a git URI with ansible-galaxy The documentation for ansible-galaxy indicates the following: The ansible-galaxy command comes bundled with Ansible, and you can use it to install roles from Galaxy or directly from a git based SCM. You can also use it to create a new role, remove roles, or perform tasks on the Galaxy website. I'm trying to figure out how it's possible to install an Ansible collection " directly from a git based SCM " as indicated. When I run ansible-galaxy collections --help , from Ansible 2.9.1 on MacOS Catalina, I see the following: usage: ansible-galaxy collection install [-h] [-s API_SERVER] [--api-key API_KEY] [-c] [-v] [-f] [-i] [-n | --force-with-deps] [-p COLLECTIONS_PATH] [-r REQUIREMENTS] [collection_name [collection_name ...]] positional arguments: collection_name The collection(s) name or path/url to a tar.gz collection artifact. This is mutually exclusive with --requirements-file. optional arguments: -h, --help show this help message and exit -s API_SERVER, --server API_SERVER The Galaxy API server URL --api-key API_KEY The Ansible Galaxy API key which can be found at [URL] You can also use ansible-galaxy login to retrieve this key or set the token for the GALAXY_SERVER_LIST entry. -c, --ignore-certs Ignore SSL certificate validation errors. -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) -f, --force Force overwriting an existing role or collection -i, --ignore-errors Ignore errors during installation and continue with the next specified collection. This will not ignore dependency conflict errors. -n, --no-deps Don't download collections listed as dependencies. --force-with-deps Force overwriting an existing collection and its dependencies. -p COLLECTIONS_PATH, --collections-path COLLECTIONS_PATH The path to the directory containing your collections. -r REQUIREMENTS, --requirements-file REQUIREMENTS A file containing a list of collections to be installed. I tried specifying a GitHub repository URI for the -p parameter, but instead of recognizing a valid URI, ansible-galaxy tried to look in a subfolder named the URI that I specified. ansible-galaxy collection install -p [URL] trevor.trevormacos My expectation would be that specifying a GitHub repository URI for the -p parameter should properly indicate that I want to install a collection from that GitHub repository . Question : How do I instruct ansible-galaxy to install an Ansible collection directly from a GitHub URI ?
|
ansible, ansible-galaxy
| 18
| 19,097
| 2
|
https://stackoverflow.com/questions/59003007/install-ansible-collections-directly-from-a-git-uri-with-ansible-galaxy
|
37,878,067
|
Ansible: Provided hosts list is empty
|
I have this below playbook where the remote host is an user input and subsequently I am trying to gather facts about the remote host and copy the same to a file in local: --- - hosts: localhost vars_prompt: name: hostname prompt: "Enter Hostname" tasks: - name: Add hosts to known_hosts file add_host: name={{ hostname }} groups=new - name: Check if Host is reachable shell: ansible -m ping {{ hostname }} - name: Remove existing remote hosts shell: ssh-keygen -R {{ hostname }} - name: Setup passwordless SSH login shell: ssh-copy-id -i ~/.ssh/id_rsa user@{{ hostname }} - name: Display facts command: ansible {{ groups['new'] }} -m setup register: output - copy: content="{{ output }}" dest=/var/tmp/dir/Node_Health/temp ... I get the below error in the temp file: Node_Health]# cat temp {"start": "2016-06-17 09:26:59.174155", "delta": "0:00:00.279268", "cmd": ["ansible", "[udl360x4675]", "-m", "setup"], "end": "2016-06-17 09:26:59.453423", "stderr": " [WARNING]: provided hosts list is empty, only localhost is available", "stdout": "", "stdout_lines": [], "changed": true, "rc": 0, "warnings": I also tried the below playbook which also gives the same error: --- - hosts: localhost vars_prompt: name: hostname prompt: "Enter Hostname" tasks: - name: Add hosts to known_hosts file add_host: name={{ hostname }} groups=new - name: Check if Host is reachable shell: ansible -m ping {{ hostname }} - name: Remove existing remote hosts shell: ssh-keygen -R {{ hostname }} - name: Setup passwordless SSH login shell: ssh-copy-id -i ~/.ssh/id_rsa user@{{ hostname }} - hosts: new tasks: - name: Display facts command: ansible {{ groups['new'] }} -m setup register: output - local_action: copy content="{{ output }}" dest=/var/tmp/dir/Node_Health/temp ... Any help will be appreciated.
|
Ansible: Provided hosts list is empty I have this below playbook where the remote host is an user input and subsequently I am trying to gather facts about the remote host and copy the same to a file in local: --- - hosts: localhost vars_prompt: name: hostname prompt: "Enter Hostname" tasks: - name: Add hosts to known_hosts file add_host: name={{ hostname }} groups=new - name: Check if Host is reachable shell: ansible -m ping {{ hostname }} - name: Remove existing remote hosts shell: ssh-keygen -R {{ hostname }} - name: Setup passwordless SSH login shell: ssh-copy-id -i ~/.ssh/id_rsa user@{{ hostname }} - name: Display facts command: ansible {{ groups['new'] }} -m setup register: output - copy: content="{{ output }}" dest=/var/tmp/dir/Node_Health/temp ... I get the below error in the temp file: Node_Health]# cat temp {"start": "2016-06-17 09:26:59.174155", "delta": "0:00:00.279268", "cmd": ["ansible", "[udl360x4675]", "-m", "setup"], "end": "2016-06-17 09:26:59.453423", "stderr": " [WARNING]: provided hosts list is empty, only localhost is available", "stdout": "", "stdout_lines": [], "changed": true, "rc": 0, "warnings": I also tried the below playbook which also gives the same error: --- - hosts: localhost vars_prompt: name: hostname prompt: "Enter Hostname" tasks: - name: Add hosts to known_hosts file add_host: name={{ hostname }} groups=new - name: Check if Host is reachable shell: ansible -m ping {{ hostname }} - name: Remove existing remote hosts shell: ssh-keygen -R {{ hostname }} - name: Setup passwordless SSH login shell: ssh-copy-id -i ~/.ssh/id_rsa user@{{ hostname }} - hosts: new tasks: - name: Display facts command: ansible {{ groups['new'] }} -m setup register: output - local_action: copy content="{{ output }}" dest=/var/tmp/dir/Node_Health/temp ... Any help will be appreciated.
|
ansible
| 18
| 98,726
| 4
|
https://stackoverflow.com/questions/37878067/ansible-provided-hosts-list-is-empty
|
23,525,546
|
Ansible : host in multiple groups
|
I have a host in 2 groups : pc and Servers I have 2 group_vars (pc and servers) with, in each the file packages.yml These files define the list of packages to be installed on pc hosts and on servers hosts I have a role to install default package The problem is : only the group_vars/pc/packages.yml is take into account by the role task, packages from group_vars/servers/packages.yml are not installed Of course what I want is installation of packages defined for pc and servers I do not know if it is a bug or a feature ... Thanks for your help here is the configuration : # file: production [pc] armen kerbel kerzo [servers] kerbel --- # packages on servers packages: - lftp - mercurial --- # packages on pc packages: - keepassx - lm-sensors - hddtemp
|
Ansible : host in multiple groups I have a host in 2 groups : pc and Servers I have 2 group_vars (pc and servers) with, in each the file packages.yml These files define the list of packages to be installed on pc hosts and on servers hosts I have a role to install default package The problem is : only the group_vars/pc/packages.yml is take into account by the role task, packages from group_vars/servers/packages.yml are not installed Of course what I want is installation of packages defined for pc and servers I do not know if it is a bug or a feature ... Thanks for your help here is the configuration : # file: production [pc] armen kerbel kerzo [servers] kerbel --- # packages on servers packages: - lftp - mercurial --- # packages on pc packages: - keepassx - lm-sensors - hddtemp
|
ansible
| 18
| 40,505
| 3
|
https://stackoverflow.com/questions/23525546/ansible-host-in-multiple-groups
|
23,492,032
|
Can't disable Ansible's host key checking
|
I'm using Ansible 1.5.4 to provision my Vagrant 1.4.3 box on Ubuntu 14.04 LTS . I'm getting the following error message in verbose mode: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ I can do: export ANSIBLE_HOST_KEY_CHECKING=False and I have following lines in my ~/.ansible.cfg : [defaults] host_key_checking = False But it doesn't help. What could be the problem? Thank you! UPDATE #1 I'm calling it directly like this (without using vagrant command): ansible-playbook playbook.yml -i inventory.ini --user=vagrant --ask-pass -vvvv The inventory is: [default] localhost:2222
|
Can't disable Ansible's host key checking I'm using Ansible 1.5.4 to provision my Vagrant 1.4.3 box on Ubuntu 14.04 LTS . I'm getting the following error message in verbose mode: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ I can do: export ANSIBLE_HOST_KEY_CHECKING=False and I have following lines in my ~/.ansible.cfg : [defaults] host_key_checking = False But it doesn't help. What could be the problem? Thank you! UPDATE #1 I'm calling it directly like this (without using vagrant command): ansible-playbook playbook.yml -i inventory.ini --user=vagrant --ask-pass -vvvv The inventory is: [default] localhost:2222
|
ubuntu, ssh, vagrant, ansible
| 18
| 17,576
| 2
|
https://stackoverflow.com/questions/23492032/cant-disable-ansibles-host-key-checking
|
30,761,615
|
Ansible git clone 'Permission Denied' but direct git clone working
|
I got a troubling issue with Ansible. I setup a git cloning on my environment using ssh key of my current host: - name: Add user Public Key copy: src: "/Users/alexgrs/.ssh/id_rsa.pub" dest: "/home/vagrant/.ssh/id_rsa.pub" mode: 0644 - name: Add user Private Key copy: src: "/Users/alexgrs/.ssh/id_rsa" dest: "/home/vagrant/.ssh/id_rsa" mode: 0600 - name: Clone Repository git: repo: repo.git dest: /home/vagrant/workspace/ update: true accept_hostkey: true key_file: "/home/vagrant/.ssh/id_rsa.pub" If I vagrant ssh on Vagrant and execute git pull repo it works. But when I do a vagrant provision I got the following error message: stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I'm pretty sure my publickey is not used by vangrant provision but I'm not able to detect why. Did you already see this kind of issue ? Thank you. EDIT: It seems that ansible is not doing a git clone but is trying the following command: /usr/bin/git ls-remote ssh://repo.git -h refs/heads/HEAD I tried it in my vagrant box and I have the same permission denied issue.
|
Ansible git clone 'Permission Denied' but direct git clone working I got a troubling issue with Ansible. I setup a git cloning on my environment using ssh key of my current host: - name: Add user Public Key copy: src: "/Users/alexgrs/.ssh/id_rsa.pub" dest: "/home/vagrant/.ssh/id_rsa.pub" mode: 0644 - name: Add user Private Key copy: src: "/Users/alexgrs/.ssh/id_rsa" dest: "/home/vagrant/.ssh/id_rsa" mode: 0600 - name: Clone Repository git: repo: repo.git dest: /home/vagrant/workspace/ update: true accept_hostkey: true key_file: "/home/vagrant/.ssh/id_rsa.pub" If I vagrant ssh on Vagrant and execute git pull repo it works. But when I do a vagrant provision I got the following error message: stderr: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I'm pretty sure my publickey is not used by vangrant provision but I'm not able to detect why. Did you already see this kind of issue ? Thank you. EDIT: It seems that ansible is not doing a git clone but is trying the following command: /usr/bin/git ls-remote ssh://repo.git -h refs/heads/HEAD I tried it in my vagrant box and I have the same permission denied issue.
|
git, ansible
| 18
| 9,422
| 3
|
https://stackoverflow.com/questions/30761615/ansible-git-clone-permission-denied-but-direct-git-clone-working
|
37,499,514
|
How Docker and Ansible fit together to implement Continuous Delivery/Continuous Deployment
|
I'm new to the configuration management and deployment tools. I have to implement a Continuous Delivery/Continuous Deployment tool for one of the most interesting projects I've ever put my hands on. First of all, individually, I'm comfortable with AWS , I know what Ansible is, the logic behind it and its purpose. I do not have same level of understanding of Docker but I got the idea. I went through a lot of Internet resources, but I can't get the the big picture. What I've been struggling is how they fit together. Using Ansible , I can manage my Infrastructure as Code; building EC2 instances, installing packages... I can even deploy a full application by pulling its code, modify config files and start web server. Docker is, itself, a tool that packages an application and ensures that it can be run wherever you deploy it. My problems are: How does Docker (or Ansible and Docker) extend the Continuous Integration process!? Suppose we have a source code repository, the team members finish working on a feature and they push their work. Jenkins detects this, runs all the acceptance/unit/integration test suites and if they all passed, it declares it as a stable build. How Docker fits here? I mean when the team pushes their work, does Jenkins have to pull the Docker file source coded within the app, build the image of the application, start the container and run all the tests against it or it runs the tests the classic way and if all is good then it builds the Docker image from the Docker file and saves it in a private place? Should Jenkins tag the final image using x.y.z for example!? Docker containers configuration : Suppose we have an image built by Jenkins stored somewhere, how to handle deploying the same image into different environments, and even, different configurations parameters ( Vhosts config, DB hosts, Queues URLs, S3 endpoints, etc...) What is the most flexible way to deal with this issue without breaking Docker principles? Are these configurations backed in the image when it gets build or when the container based on it is started, if so how are they injected? Ansible and Docker : Ansible provides a Docker module to manage Docker containers. Assuming I solved the problems mentioned above, when I want to deploy a new version x.t.z of my app, I tell Ansible to pull that image from where it was stored on, start the app container, so how to inject the configuration settings!? Does Ansible have to log in the Docker image, before it's running ( this sounds insane to me ) and use its Jinja2 templates the same way with a classic host!? If not, how is this handled?! Excuse me if it was a long question or if I misspelled something, but this is my thinking out loud. I'm blocked for the past two weeks and I can't figure out the correct workflow. I want this to be a reference for future readers. Please, it would very helpful to read your experiences and solutions because this looks like a common workflow.
|
How Docker and Ansible fit together to implement Continuous Delivery/Continuous Deployment I'm new to the configuration management and deployment tools. I have to implement a Continuous Delivery/Continuous Deployment tool for one of the most interesting projects I've ever put my hands on. First of all, individually, I'm comfortable with AWS , I know what Ansible is, the logic behind it and its purpose. I do not have same level of understanding of Docker but I got the idea. I went through a lot of Internet resources, but I can't get the the big picture. What I've been struggling is how they fit together. Using Ansible , I can manage my Infrastructure as Code; building EC2 instances, installing packages... I can even deploy a full application by pulling its code, modify config files and start web server. Docker is, itself, a tool that packages an application and ensures that it can be run wherever you deploy it. My problems are: How does Docker (or Ansible and Docker) extend the Continuous Integration process!? Suppose we have a source code repository, the team members finish working on a feature and they push their work. Jenkins detects this, runs all the acceptance/unit/integration test suites and if they all passed, it declares it as a stable build. How Docker fits here? I mean when the team pushes their work, does Jenkins have to pull the Docker file source coded within the app, build the image of the application, start the container and run all the tests against it or it runs the tests the classic way and if all is good then it builds the Docker image from the Docker file and saves it in a private place? Should Jenkins tag the final image using x.y.z for example!? Docker containers configuration : Suppose we have an image built by Jenkins stored somewhere, how to handle deploying the same image into different environments, and even, different configurations parameters ( Vhosts config, DB hosts, Queues URLs, S3 endpoints, etc...) What is the most flexible way to deal with this issue without breaking Docker principles? Are these configurations backed in the image when it gets build or when the container based on it is started, if so how are they injected? Ansible and Docker : Ansible provides a Docker module to manage Docker containers. Assuming I solved the problems mentioned above, when I want to deploy a new version x.t.z of my app, I tell Ansible to pull that image from where it was stored on, start the app container, so how to inject the configuration settings!? Does Ansible have to log in the Docker image, before it's running ( this sounds insane to me ) and use its Jinja2 templates the same way with a classic host!? If not, how is this handled?! Excuse me if it was a long question or if I misspelled something, but this is my thinking out loud. I'm blocked for the past two weeks and I can't figure out the correct workflow. I want this to be a reference for future readers. Please, it would very helpful to read your experiences and solutions because this looks like a common workflow.
|
amazon-web-services, docker, ansible, continuous-deployment, continuous-delivery
| 18
| 1,152
| 3
|
https://stackoverflow.com/questions/37499514/how-docker-and-ansible-fit-together-to-implement-continuous-delivery-continuous
|
23,056,177
|
Continuous deployment & AWS autoscaling using Ansible (+Docker ?)
|
My organization's website is a Django app running on front end webservers + a few background processing servers in AWS. We're currently using Ansible for both : system configuration (from a bare OS image) frequent manually-triggered code deployments. The same Ansible playbook is able to provision either a local Vagrant dev VM, or a production EC2 instance from scratch. We now want to implement autoscaling in EC2, and that requires some changes towards a "treat servers as cattle, not pets" philosophy. The first prerequisite was to move from a statically managed Ansible inventory to a dynamic, EC2 API-based one, done. The next big question is how to deploy in this new world where throwaway instances come up & down in the middle of the night. The options I can think of are : Bake a new fully-deployed AMI for each deploy , create a new AS Launch config and update the AS group with that. Sounds very, very cumbersome, but also very reliable because of the clean slate approach, and will ensure that any system changes the code requires will be here. Also, no additional steps needed on instance bootup, so up & running more quickly. Use a base AMI that doesn't change very often, automatically get the latest app code from git upon bootup, start webserver. Once it's up just do manual deploys as needed, like before. But what if the new code depends on a change in the system config (new package, permissions, etc) ? Looks like you have to start taking care of dependencies between code versions and system/AMI versions, whereas the "just do a full ansible run" approach was more integrated and more reliable. Is it more than just a potential headache in practice ? Use Docker ? I have a strong hunch it can be useful, but I'm not sure yet how it would fit our picture. We're a relatively self-contained Django front-end app with just RabbitMQ + memcache as services, which we're never going to run on the same host anyway. So what benefits are there in building a Docker image using Ansible that contains system packages + latest code, rather than having Ansible just do it directly on an EC2 instance ? How do you do it ? Any insights / best practices ? Thanks !
|
Continuous deployment & AWS autoscaling using Ansible (+Docker ?) My organization's website is a Django app running on front end webservers + a few background processing servers in AWS. We're currently using Ansible for both : system configuration (from a bare OS image) frequent manually-triggered code deployments. The same Ansible playbook is able to provision either a local Vagrant dev VM, or a production EC2 instance from scratch. We now want to implement autoscaling in EC2, and that requires some changes towards a "treat servers as cattle, not pets" philosophy. The first prerequisite was to move from a statically managed Ansible inventory to a dynamic, EC2 API-based one, done. The next big question is how to deploy in this new world where throwaway instances come up & down in the middle of the night. The options I can think of are : Bake a new fully-deployed AMI for each deploy , create a new AS Launch config and update the AS group with that. Sounds very, very cumbersome, but also very reliable because of the clean slate approach, and will ensure that any system changes the code requires will be here. Also, no additional steps needed on instance bootup, so up & running more quickly. Use a base AMI that doesn't change very often, automatically get the latest app code from git upon bootup, start webserver. Once it's up just do manual deploys as needed, like before. But what if the new code depends on a change in the system config (new package, permissions, etc) ? Looks like you have to start taking care of dependencies between code versions and system/AMI versions, whereas the "just do a full ansible run" approach was more integrated and more reliable. Is it more than just a potential headache in practice ? Use Docker ? I have a strong hunch it can be useful, but I'm not sure yet how it would fit our picture. We're a relatively self-contained Django front-end app with just RabbitMQ + memcache as services, which we're never going to run on the same host anyway. So what benefits are there in building a Docker image using Ansible that contains system packages + latest code, rather than having Ansible just do it directly on an EC2 instance ? How do you do it ? Any insights / best practices ? Thanks !
|
amazon-ec2, docker, ansible, continuous-deployment, autoscaling
| 18
| 5,991
| 3
|
https://stackoverflow.com/questions/23056177/continuous-deployment-aws-autoscaling-using-ansible-docker
|
24,504,430
|
Ansible prompts password when using synchronize
|
I'm using ansible in the following way: ansible-playbook -f 1 my-play-book.yaml --ask-pass --ask-sudo-pass After this I'm asked to enter the ssh & sudo passwords (same password for both). Inside my playbook file I'm using synchronize task: synchronize: mode=push src=rel/path/myfolder/ dest=/abs/path/myfolder/ For each host, I'm prompted to enter the ssh password of the remote host (the same that I entered in the beginning of the playbook run) How can I avoid entering the password when executing synchronize task?
|
Ansible prompts password when using synchronize I'm using ansible in the following way: ansible-playbook -f 1 my-play-book.yaml --ask-pass --ask-sudo-pass After this I'm asked to enter the ssh & sudo passwords (same password for both). Inside my playbook file I'm using synchronize task: synchronize: mode=push src=rel/path/myfolder/ dest=/abs/path/myfolder/ For each host, I'm prompted to enter the ssh password of the remote host (the same that I entered in the beginning of the playbook run) How can I avoid entering the password when executing synchronize task?
|
ssh, passwords, rsync, synchronize, ansible
| 18
| 5,723
| 1
|
https://stackoverflow.com/questions/24504430/ansible-prompts-password-when-using-synchronize
|
35,969,668
|
Ansible: path to ansible.cfg
|
I have this known issue. So I try to fix it but I don't see where I have to create my ansible.cfg (or does it already exist)? I tried it in my homedirectory but it still did not work. sudo vi ~/.ansible.cfg I read a lot about /etc/ansible but on my system it isn't there. I'm on Mac El Capitan. I've installed ansible by using pip . ansible --version ansible 1.9.4 configured module search path = None
|
Ansible: path to ansible.cfg I have this known issue. So I try to fix it but I don't see where I have to create my ansible.cfg (or does it already exist)? I tried it in my homedirectory but it still did not work. sudo vi ~/.ansible.cfg I read a lot about /etc/ansible but on my system it isn't there. I'm on Mac El Capitan. I've installed ansible by using pip . ansible --version ansible 1.9.4 configured module search path = None
|
ansible
| 17
| 67,744
| 4
|
https://stackoverflow.com/questions/35969668/ansible-path-to-ansible-cfg
|
56,508,435
|
How to concatenate with a string each element of a list in ansible
|
I've got a list of string element in a ansible var. I'm looking how to append to each element of the list with a defined string. Do you know how I can do? I didn't find a way to do so. Input: [ "a", "b", "c" ] Output: [ "a-Z", "b-Z", "c-Z" ]
|
How to concatenate with a string each element of a list in ansible I've got a list of string element in a ansible var. I'm looking how to append to each element of the list with a defined string. Do you know how I can do? I didn't find a way to do so. Input: [ "a", "b", "c" ] Output: [ "a-Z", "b-Z", "c-Z" ]
|
ansible, jinja2
| 17
| 26,507
| 6
|
https://stackoverflow.com/questions/56508435/how-to-concatenate-with-a-string-each-element-of-a-list-in-ansible
|
47,391,150
|
Ansible local_action directive
|
I'm quite new to Ansible and have a simple question for my understanding of local_action directive. Would that mean that the command is fully executed locally? Let's say you have something like this: local_action: command which nginx register: check_nginx failed_when: no changed_when: no Then you have another block looking for nginx's existence with something like that: - fail: msg="nginx unavailable" when: check_nginx.rc == 1 Does that mean that playbook will fail in case nginx is not installed locally or will it fail if is not installed remotely ?
|
Ansible local_action directive I'm quite new to Ansible and have a simple question for my understanding of local_action directive. Would that mean that the command is fully executed locally? Let's say you have something like this: local_action: command which nginx register: check_nginx failed_when: no changed_when: no Then you have another block looking for nginx's existence with something like that: - fail: msg="nginx unavailable" when: check_nginx.rc == 1 Does that mean that playbook will fail in case nginx is not installed locally or will it fail if is not installed remotely ?
|
ansible
| 17
| 58,962
| 2
|
https://stackoverflow.com/questions/47391150/ansible-local-action-directive
|
58,169,348
|
How is the architecture fact called in Ansible?
|
I am looking for the fact, which contains the following information: $ dpkg --print-architecture amd64 I can not find it: $ ansible host -m setup | grep amd64 "BOOT_IMAGE": "/boot/vmlinuz-4.19.0-6-amd64", "ansible_kernel": "4.19.0-6-amd64", "BOOT_IMAGE": "/boot/vmlinuz-4.19.0-6-amd64",
|
How is the architecture fact called in Ansible? I am looking for the fact, which contains the following information: $ dpkg --print-architecture amd64 I can not find it: $ ansible host -m setup | grep amd64 "BOOT_IMAGE": "/boot/vmlinuz-4.19.0-6-amd64", "ansible_kernel": "4.19.0-6-amd64", "BOOT_IMAGE": "/boot/vmlinuz-4.19.0-6-amd64",
|
ansible
| 17
| 9,231
| 3
|
https://stackoverflow.com/questions/58169348/how-is-the-architecture-fact-called-in-ansible
|
39,800,368
|
Test if a server is reachable from host and has port open with Ansible
|
I want to test if the host I am provisioning can reach a specific server and connect to a specific TCP port. If it can't the playbook should fail. How can I do that?
|
Test if a server is reachable from host and has port open with Ansible I want to test if the host I am provisioning can reach a specific server and connect to a specific TCP port. If it can't the playbook should fail. How can I do that?
|
ansible
| 17
| 65,631
| 3
|
https://stackoverflow.com/questions/39800368/test-if-a-server-is-reachable-from-host-and-has-port-open-with-ansible
|
24,496,362
|
Configure Ansible roles with dependent roles
|
The problem is best described with an example: There are two roles: mailserver : a basic mail server configuration mailinglist : mailing list application The mailing list software needs the mailserver to transport incoming mails to the mailing list software's "virtual inbox". This requires some configuration of the mail server. But the mailserver does not know about the mailing list role, nor other roles with similar configuration requirements. What I would like to do is this: mailinglist (and other similar roles) stores the transport configuration in a variable transport_config . This could be a "transport map" like $email => $spool. mailinglist depends on the mailserver role. mailserver configures it's "transport" using the variable transport_config . Is there a way to do something like this in Ansible? Or another solution to this problem? It's not possible to use role variables like {role: mailserver, transport_config: ...} , as there may be more than one role depending on the mailserver. What I can think of is a workaround: The mailserver reads/parses a configuration directory where transport maps are defined. mailinglist and other roles add files to this directory. The problem here is that this often requires a "configuration builder" which reads such configuration directories and generates the main configuration file.
|
Configure Ansible roles with dependent roles The problem is best described with an example: There are two roles: mailserver : a basic mail server configuration mailinglist : mailing list application The mailing list software needs the mailserver to transport incoming mails to the mailing list software's "virtual inbox". This requires some configuration of the mail server. But the mailserver does not know about the mailing list role, nor other roles with similar configuration requirements. What I would like to do is this: mailinglist (and other similar roles) stores the transport configuration in a variable transport_config . This could be a "transport map" like $email => $spool. mailinglist depends on the mailserver role. mailserver configures it's "transport" using the variable transport_config . Is there a way to do something like this in Ansible? Or another solution to this problem? It's not possible to use role variables like {role: mailserver, transport_config: ...} , as there may be more than one role depending on the mailserver. What I can think of is a workaround: The mailserver reads/parses a configuration directory where transport maps are defined. mailinglist and other roles add files to this directory. The problem here is that this often requires a "configuration builder" which reads such configuration directories and generates the main configuration file.
|
ansible, ansible-role
| 17
| 26,466
| 5
|
https://stackoverflow.com/questions/24496362/configure-ansible-roles-with-dependent-roles
|
70,202,432
|
Getting a python warning when running playbook EC2 inventory
|
I am really new to Ansible and I hate getting warnings when I run a playbook. This environment is being used for my education. Environment: AWS EC2 4 Ubuntu 20 3 Amazon Linux2 hosts Inventory using the dynamic inventory script playbook just runs a simple ping against all hosts. I wanted to test the inventory warning [WARNING]: Platform linux on host XXXXXX.amazonaws.com is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change the meaning of that path. See [URL] for more information. Things I have tried updated all sym links on hosts to point to the python3 version adding the line "ansible_python_interpreter = /usr/bin/python" to "/etc/ansible/ansible.cfg" I am relying on that cfg file I would like to know how to solve this. since I am not running a static inventory, I didn't think that I could specific an interpreter on a per host or group of hosts. While the playbook runs, it seems that something is not configured correctly and I would like to get that sorted. This is only present on the Amazon Linux instances. the Ubuntu instances are fine. Michael
|
Getting a python warning when running playbook EC2 inventory I am really new to Ansible and I hate getting warnings when I run a playbook. This environment is being used for my education. Environment: AWS EC2 4 Ubuntu 20 3 Amazon Linux2 hosts Inventory using the dynamic inventory script playbook just runs a simple ping against all hosts. I wanted to test the inventory warning [WARNING]: Platform linux on host XXXXXX.amazonaws.com is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change the meaning of that path. See [URL] for more information. Things I have tried updated all sym links on hosts to point to the python3 version adding the line "ansible_python_interpreter = /usr/bin/python" to "/etc/ansible/ansible.cfg" I am relying on that cfg file I would like to know how to solve this. since I am not running a static inventory, I didn't think that I could specific an interpreter on a per host or group of hosts. While the playbook runs, it seems that something is not configured correctly and I would like to get that sorted. This is only present on the Amazon Linux instances. the Ubuntu instances are fine. Michael
|
ansible, ansible-inventory
| 17
| 35,272
| 3
|
https://stackoverflow.com/questions/70202432/getting-a-python-warning-when-running-playbook-ec2-inventory
|
60,304,415
|
Ansible, how to check if a variable is not null?
|
I have this var I a role that I use to add authorized keys to a linux user, so foo can either be a string with a single ssh public key or a list of multiple public keys. By default foo is defined but empty so it can be tested even if the user doesn't set it, that way no related tasks are done if it's empty. I'd normaly use when: foo or when: not foo and it was working great, except that now ansible trow a depreciation warning saying : [DEPRECATION WARNING]: evaluating None as a bare variable, this behaviour will go away and you might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle.. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. I tried when: foo|bool as mentionned but it returns false every time the variable is filled with a string that's not yes, true, Yes... foo is defined doesn't work since the var is defined foo != "" doesn't work because the var is null not a empty string foo | length > 0 doesn't work because null doesn't have a length I'm honestly out of ideas here.
|
Ansible, how to check if a variable is not null? I have this var I a role that I use to add authorized keys to a linux user, so foo can either be a string with a single ssh public key or a list of multiple public keys. By default foo is defined but empty so it can be tested even if the user doesn't set it, that way no related tasks are done if it's empty. I'd normaly use when: foo or when: not foo and it was working great, except that now ansible trow a depreciation warning saying : [DEPRECATION WARNING]: evaluating None as a bare variable, this behaviour will go away and you might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle.. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. I tried when: foo|bool as mentionned but it returns false every time the variable is filled with a string that's not yes, true, Yes... foo is defined doesn't work since the var is defined foo != "" doesn't work because the var is null not a empty string foo | length > 0 doesn't work because null doesn't have a length I'm honestly out of ideas here.
|
ansible
| 17
| 58,288
| 3
|
https://stackoverflow.com/questions/60304415/ansible-how-to-check-if-a-variable-is-not-null
|
34,492,139
|
how to define login user and become root in playbook
|
my loginuser is user1 and i want to execute the playbook with root. how can i do this. if i use in cmdline it does not work like this ansible-playbook main.yaml -i hosts --user=git -k --become-user=root --ask-become-pass --become-method=su Please tell me how to implement this. name: Install and Configure IEM hosts: rhel ansible_become: yes ansible_become_method: su ansible_become_user: root ansible_become_pass: passw0rd tasks: - name: Creating masthead file path file: path=/etc/opt/BESClient state=directory - name: Creating install directory
|
how to define login user and become root in playbook my loginuser is user1 and i want to execute the playbook with root. how can i do this. if i use in cmdline it does not work like this ansible-playbook main.yaml -i hosts --user=git -k --become-user=root --ask-become-pass --become-method=su Please tell me how to implement this. name: Install and Configure IEM hosts: rhel ansible_become: yes ansible_become_method: su ansible_become_user: root ansible_become_pass: passw0rd tasks: - name: Creating masthead file path file: path=/etc/opt/BESClient state=directory - name: Creating install directory
|
ansible
| 17
| 70,903
| 5
|
https://stackoverflow.com/questions/34492139/how-to-define-login-user-and-become-root-in-playbook
|
36,667,042
|
Ansible: How to specify an array or list element fact with yaml?
|
When we check hostvars with: - name: Display all variables/facts known for a host debug: var=hostvars[inventory_hostname] We get: ok: [default] => { "hostvars[inventory_hostname]": { "admin_email": "admin@surfer190.com", "admin_user": "root", "ansible_all_ipv4_addresses": [ "192.168.35.19", "10.0.2.15" ],... How would I specify the first element of the "ansible_all_ipv4_addresses" list?
|
Ansible: How to specify an array or list element fact with yaml? When we check hostvars with: - name: Display all variables/facts known for a host debug: var=hostvars[inventory_hostname] We get: ok: [default] => { "hostvars[inventory_hostname]": { "admin_email": "admin@surfer190.com", "admin_user": "root", "ansible_all_ipv4_addresses": [ "192.168.35.19", "10.0.2.15" ],... How would I specify the first element of the "ansible_all_ipv4_addresses" list?
|
ansible, yaml, ansible-facts
| 17
| 44,312
| 3
|
https://stackoverflow.com/questions/36667042/ansible-how-to-specify-an-array-or-list-element-fact-with-yaml
|
46,198,479
|
Proper way to define default variables for all hosts in Ansible
|
There is a definition of [all:vars] in my ansible inventory file as follows: [all:vars] ansible_shell_type=bash ansible_user=certain_user ansible_ssh_common_args="-o ConnectionAttempts=10" I plan to move such variables into ansible.cfg to set defaults for all hosts. Would it simply work in a similar way or is there any circumstances to consider? What else alternatives available to remove [all:vars] from the inventory file?
|
Proper way to define default variables for all hosts in Ansible There is a definition of [all:vars] in my ansible inventory file as follows: [all:vars] ansible_shell_type=bash ansible_user=certain_user ansible_ssh_common_args="-o ConnectionAttempts=10" I plan to move such variables into ansible.cfg to set defaults for all hosts. Would it simply work in a similar way or is there any circumstances to consider? What else alternatives available to remove [all:vars] from the inventory file?
|
ansible, ansible-inventory
| 17
| 24,641
| 3
|
https://stackoverflow.com/questions/46198479/proper-way-to-define-default-variables-for-all-hosts-in-ansible
|
44,592,141
|
Ansible ad-hoc command with direct host specified - no hosts matched
|
I am running a 16.04 Ubuntu desktop machine using VirtualBox. This VM has Ansible 2.4.0 installed. I am trying to run an ad-hoc ansible command just to prove it works (I am doing an online course). To simulate a small server farm, I use lxc (linux containters) and have three of them running: root@tomasz-VirtualBox:/home/tomasz/ansible# lxc-ls --fancy NAME STATE AUTOSTART GROUPS IPV4 IPV6 db1 RUNNING 0 - 10.0.3.248 - web1 RUNNING 0 - 10.0.3.110 - web2 RUNNING 0 - 10.0.3.226 - I can SSH to any of these servers, however when I try to run a one-off ansible command, for example: root@tomasz-VirtualBox:/home/tomasz/ansible# ansible 10.0.3.248 -m ping -u ubuntu I get the following errors, that no inventory has been matched: [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available [WARNING]: Could not match supplied host pattern, ignoring: 10.0.3.248 [WARNING]: No hosts matched, nothing to do I am puzzled, to be honest, and as an Ansible novice, I have no idea how to move this forward. Seems such a simple issue, have not come across any similar thing here on stackoverflow. Many thanks for any hints!
|
Ansible ad-hoc command with direct host specified - no hosts matched I am running a 16.04 Ubuntu desktop machine using VirtualBox. This VM has Ansible 2.4.0 installed. I am trying to run an ad-hoc ansible command just to prove it works (I am doing an online course). To simulate a small server farm, I use lxc (linux containters) and have three of them running: root@tomasz-VirtualBox:/home/tomasz/ansible# lxc-ls --fancy NAME STATE AUTOSTART GROUPS IPV4 IPV6 db1 RUNNING 0 - 10.0.3.248 - web1 RUNNING 0 - 10.0.3.110 - web2 RUNNING 0 - 10.0.3.226 - I can SSH to any of these servers, however when I try to run a one-off ansible command, for example: root@tomasz-VirtualBox:/home/tomasz/ansible# ansible 10.0.3.248 -m ping -u ubuntu I get the following errors, that no inventory has been matched: [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available [WARNING]: Could not match supplied host pattern, ignoring: 10.0.3.248 [WARNING]: No hosts matched, nothing to do I am puzzled, to be honest, and as an Ansible novice, I have no idea how to move this forward. Seems such a simple issue, have not come across any similar thing here on stackoverflow. Many thanks for any hints!
|
linux, ansible, ansible-2.x
| 17
| 29,649
| 1
|
https://stackoverflow.com/questions/44592141/ansible-ad-hoc-command-with-direct-host-specified-no-hosts-matched
|
44,142,208
|
How to view/decrypt Ansible vault credentials files from within a Python script?
|
I'm trying to figure out how to provide the following facilities to a Python script so that it can: Import Ansible Python modules Open up my defined ansible.cfg and read vault_password_file variable Read vault_password_file and temporarily store in a Python variable Decrypt a referenced Ansible vaulted file I found this code via google but it did not appear to work when I tried it: import ansible.utils bar = dict() bar = ansible.utils._load_vars_from_path("secrets.yml", results=bar, vault_password="password") print bar Throws this error: $ python ansible-vault-ex.py Traceback (most recent call last): File "ansible-vault-ex.py", line 5, in <module> bar = ansible.utils._load_vars_from_path("credentials.vault", results=bar, vault_password="password") AttributeError: 'module' object has no attribute '_load_vars_from_path' When I investigated this I saw no indications of this function in any Ansible related files, leading me to believe that this method no longer worked with some newer version(s) of Ansible. Bottom line is that I'd like some method for importing Ansible libraries/modules from a Python script, so that I can interact with ansible-vault managed files programmatically from Python.
|
How to view/decrypt Ansible vault credentials files from within a Python script? I'm trying to figure out how to provide the following facilities to a Python script so that it can: Import Ansible Python modules Open up my defined ansible.cfg and read vault_password_file variable Read vault_password_file and temporarily store in a Python variable Decrypt a referenced Ansible vaulted file I found this code via google but it did not appear to work when I tried it: import ansible.utils bar = dict() bar = ansible.utils._load_vars_from_path("secrets.yml", results=bar, vault_password="password") print bar Throws this error: $ python ansible-vault-ex.py Traceback (most recent call last): File "ansible-vault-ex.py", line 5, in <module> bar = ansible.utils._load_vars_from_path("credentials.vault", results=bar, vault_password="password") AttributeError: 'module' object has no attribute '_load_vars_from_path' When I investigated this I saw no indications of this function in any Ansible related files, leading me to believe that this method no longer worked with some newer version(s) of Ansible. Bottom line is that I'd like some method for importing Ansible libraries/modules from a Python script, so that I can interact with ansible-vault managed files programmatically from Python.
|
python, encryption, ansible, ansible-vault
| 17
| 29,681
| 7
|
https://stackoverflow.com/questions/44142208/how-to-view-decrypt-ansible-vault-credentials-files-from-within-a-python-script
|
35,332,188
|
running an Ansible playbook against a single host
|
I'm using a hosts file for static inventory: server1 ansible_ssh_host=1.1.1.1 server2 ansible_ssh_host=1.1.1.2 server3 ansible_ssh_host=1.1.1.3 [group1] server1 server2 And I've got a playbook example.yml like this: --- - name: base setup become: true hosts: - group1 roles: - base I'd like to an ansible-playbook test run using example.yml , but only against the host server1 . Is there a way of doing this?
|
running an Ansible playbook against a single host I'm using a hosts file for static inventory: server1 ansible_ssh_host=1.1.1.1 server2 ansible_ssh_host=1.1.1.2 server3 ansible_ssh_host=1.1.1.3 [group1] server1 server2 And I've got a playbook example.yml like this: --- - name: base setup become: true hosts: - group1 roles: - base I'd like to an ansible-playbook test run using example.yml , but only against the host server1 . Is there a way of doing this?
|
ansible
| 17
| 43,425
| 1
|
https://stackoverflow.com/questions/35332188/running-an-ansible-playbook-against-a-single-host
|
35,281,785
|
Jinja2 filter list using string contains test
|
I'm trying to filter a list in ansible in Jinja2 when the elements contain a string, but the Jinja documentation doesn't seem clear enough for me to figure it out. This is what I have so far: - name: run script command: /usr/tmp/run_script.py register: script_results - name: display run info debug: var: "{{script_results.stdout_lines | select(\"'running script' in script_results.stdout_lines\") }}" But all I get is the error: "<generator object _select_or_reject at 0x13851e0>": "VARIABLE IS NOT DEFINED!" So for example, if stdout_lines contains ["apples","running script one","oranges","running script two"] , I want to print running script one running script two They have documentation for select and documentation for built-in-tests , but they don't display the "in" test, and I don't know how they work in the context of this ansible variable. I tried solving it like this: - name: display run info debug: var: item with_items: "{{script_results.stdout_lines}}" when: "'running script' in item" But that displays "skipping" for every line that doesn't pass the test ... kinda defeating the purpose!
|
Jinja2 filter list using string contains test I'm trying to filter a list in ansible in Jinja2 when the elements contain a string, but the Jinja documentation doesn't seem clear enough for me to figure it out. This is what I have so far: - name: run script command: /usr/tmp/run_script.py register: script_results - name: display run info debug: var: "{{script_results.stdout_lines | select(\"'running script' in script_results.stdout_lines\") }}" But all I get is the error: "<generator object _select_or_reject at 0x13851e0>": "VARIABLE IS NOT DEFINED!" So for example, if stdout_lines contains ["apples","running script one","oranges","running script two"] , I want to print running script one running script two They have documentation for select and documentation for built-in-tests , but they don't display the "in" test, and I don't know how they work in the context of this ansible variable. I tried solving it like this: - name: display run info debug: var: item with_items: "{{script_results.stdout_lines}}" when: "'running script' in item" But that displays "skipping" for every line that doesn't pass the test ... kinda defeating the purpose!
|
jinja2, ansible, ansible-2.x
| 17
| 59,263
| 5
|
https://stackoverflow.com/questions/35281785/jinja2-filter-list-using-string-contains-test
|
32,146,722
|
remove all files containing a certain name within a directory
|
I have the following directory and it has the following files: /tmp/test/file1.txt /tmp/test/file1.txt.backup /tmp/test/mywords.csv How do I use the file module to just remove file1* files?
|
remove all files containing a certain name within a directory I have the following directory and it has the following files: /tmp/test/file1.txt /tmp/test/file1.txt.backup /tmp/test/mywords.csv How do I use the file module to just remove file1* files?
|
ansible
| 17
| 35,738
| 4
|
https://stackoverflow.com/questions/32146722/remove-all-files-containing-a-certain-name-within-a-directory
|
48,514,072
|
How to automatically pass vault password when running Ansible playbook?
|
I have an Ansible playbook with vault, and I want to ask for vault password through the prompt box in my web interface and then pass the posted password when running ansible playbook. I tried to use: echo $password | ansible-playbook test.yml --ask-vault-pass to pass the password to the playbook, but it doesn't work, the error message is: "msg": "Attempting to decrypt but no vault secrets found" I don't want to store password in file for some resons and now I just want to try to automatically pass password to the playbook while running it. Is there any advice to me? The ansible version is 2.4.
|
How to automatically pass vault password when running Ansible playbook? I have an Ansible playbook with vault, and I want to ask for vault password through the prompt box in my web interface and then pass the posted password when running ansible playbook. I tried to use: echo $password | ansible-playbook test.yml --ask-vault-pass to pass the password to the playbook, but it doesn't work, the error message is: "msg": "Attempting to decrypt but no vault secrets found" I don't want to store password in file for some resons and now I just want to try to automatically pass password to the playbook while running it. Is there any advice to me? The ansible version is 2.4.
|
ansible, ansible-vault
| 17
| 38,304
| 5
|
https://stackoverflow.com/questions/48514072/how-to-automatically-pass-vault-password-when-running-ansible-playbook
|
37,287,013
|
How to convert a dictionary of dictionaries into a list of dictionaries in a Ansible vars file?
|
Within an Ansible vars file, I want to convert a dict of dicts into a list of dicts that I can pass to an external role from Ansible Galaxy. Input: postgres_users: dc1: name: user_dc1 password: pass_dc1 dc2: name: user_dc2 password: pass_dc2 dc3: name: user_dc3 password: pass_dc3 Desired output: postgres_users: - name: user_dc1 password: pass_dc1 - name: user_dc2 password: pass_dc2 - name: user_dc3 password: pass_dc3 Is there a simple way to do this within an Ansible vars file?
|
How to convert a dictionary of dictionaries into a list of dictionaries in a Ansible vars file? Within an Ansible vars file, I want to convert a dict of dicts into a list of dicts that I can pass to an external role from Ansible Galaxy. Input: postgres_users: dc1: name: user_dc1 password: pass_dc1 dc2: name: user_dc2 password: pass_dc2 dc3: name: user_dc3 password: pass_dc3 Desired output: postgres_users: - name: user_dc1 password: pass_dc1 - name: user_dc2 password: pass_dc2 - name: user_dc3 password: pass_dc3 Is there a simple way to do this within an Ansible vars file?
|
dictionary, ansible, jinja2, ansible-2.x
| 17
| 30,910
| 1
|
https://stackoverflow.com/questions/37287013/how-to-convert-a-dictionary-of-dictionaries-into-a-list-of-dictionaries-in-a-ans
|
41,271,525
|
Ansible installation of Debian packages
|
I'm trying to install a Debian package via Ansible apt task: - name: Install prince apt: deb: [URL] However, I get the message: SystemError: E:Could not open file [URL] - open (2: No such file or directory), E:Unable to determine file size for fd -1 - fstat (9: Bad file descriptor), E:Read error - read (9: Bad file descriptor) The URL is valid. I can download to my local, using that link. I can install using dpkg -i . However that ansible task doesn't work. Thanks in advance.
|
Ansible installation of Debian packages I'm trying to install a Debian package via Ansible apt task: - name: Install prince apt: deb: [URL] However, I get the message: SystemError: E:Could not open file [URL] - open (2: No such file or directory), E:Unable to determine file size for fd -1 - fstat (9: Bad file descriptor), E:Read error - read (9: Bad file descriptor) The URL is valid. I can download to my local, using that link. I can install using dpkg -i . However that ansible task doesn't work. Thanks in advance.
|
ansible
| 17
| 28,549
| 2
|
https://stackoverflow.com/questions/41271525/ansible-installation-of-debian-packages
|
36,403,735
|
How to get environment variables of remote host
|
I am having problems working with the environment variables of a remote host. For example, when I try {{ lookup('env', 'PATH') }} this returns the path of my guest machine not of the remote host. How to pick up / change environment variables of the remote host? my playbook : --- - name : playbook hosts : webservers gather_facts: yes remote_user: user1 vars: Path: "{{lookup('ansible_env','PATH')}}" roles : - task1 - task2 - task3 that's return the path of my machine not the path of remote host named user1 i'm a beginner in ansible need some help . thank you in advance.
|
How to get environment variables of remote host I am having problems working with the environment variables of a remote host. For example, when I try {{ lookup('env', 'PATH') }} this returns the path of my guest machine not of the remote host. How to pick up / change environment variables of the remote host? my playbook : --- - name : playbook hosts : webservers gather_facts: yes remote_user: user1 vars: Path: "{{lookup('ansible_env','PATH')}}" roles : - task1 - task2 - task3 that's return the path of my machine not the path of remote host named user1 i'm a beginner in ansible need some help . thank you in advance.
|
linux, environment-variables, yaml, ansible
| 17
| 23,780
| 2
|
https://stackoverflow.com/questions/36403735/how-to-get-environment-variables-of-remote-host
|
22,476,097
|
How to mention wildcard in ansible commands
|
I am executing shell commands via Ansible. Sometimes i don't have the complete foldername. Suppose i have dirname solr4.7.0 . In shell I can type cd solr* . But in ansible I can't do: chdir=/var/solr* Is there any workaround?
|
How to mention wildcard in ansible commands I am executing shell commands via Ansible. Sometimes i don't have the complete foldername. Suppose i have dirname solr4.7.0 . In shell I can type cd solr* . But in ansible I can't do: chdir=/var/solr* Is there any workaround?
|
linux, ansible
| 17
| 29,368
| 5
|
https://stackoverflow.com/questions/22476097/how-to-mention-wildcard-in-ansible-commands
|
29,495,704
|
How do you change ansible_default_ipv4?
|
I'd like to change ansible_default_ipv4 to point to eth1 instead of eth0. Can I do this in either the playbook or via the --extra-vars option?
|
How do you change ansible_default_ipv4? I'd like to change ansible_default_ipv4 to point to eth1 instead of eth0. Can I do this in either the playbook or via the --extra-vars option?
|
ansible, ansible-facts
| 17
| 27,149
| 3
|
https://stackoverflow.com/questions/29495704/how-do-you-change-ansible-default-ipv4
|
42,877,391
|
Display banner message in Ansible
|
I want to display a banner message in Ansible after completion of running a playbook, giving instructions for next steps. This is what i have done: - name: display post install message debug: msg: | Things left to do: - enable dash to dock gnome plugin in gnome tweal tool - install SpaceVim plugins: vim "+call dein#install()" +qa - git clone the dotfiles repo But this gives an ugly output like this: TASK [display post install message] ******************************************** ok: [localhost] => { "msg": "Things left to do:\n- enable dash to dock gnome plugin in gnome tweal tool\n- install SpaceVim plugins: vim \"+call dein#install()\" +qa\n- git clone the dotfiles repo\n" } PLAY RECAP ********************************************************************* localhost : ok=2 changed=0 unreachable=0 failed=0 Is there a better a way to display post run message?
|
Display banner message in Ansible I want to display a banner message in Ansible after completion of running a playbook, giving instructions for next steps. This is what i have done: - name: display post install message debug: msg: | Things left to do: - enable dash to dock gnome plugin in gnome tweal tool - install SpaceVim plugins: vim "+call dein#install()" +qa - git clone the dotfiles repo But this gives an ugly output like this: TASK [display post install message] ******************************************** ok: [localhost] => { "msg": "Things left to do:\n- enable dash to dock gnome plugin in gnome tweal tool\n- install SpaceVim plugins: vim \"+call dein#install()\" +qa\n- git clone the dotfiles repo\n" } PLAY RECAP ********************************************************************* localhost : ok=2 changed=0 unreachable=0 failed=0 Is there a better a way to display post run message?
|
ansible
| 17
| 23,880
| 3
|
https://stackoverflow.com/questions/42877391/display-banner-message-in-ansible
|
41,178,361
|
How to use Ansible git module pull a branch with local changes?
|
My git workspace is dirty, there are some local modifications. When I use command git pull origin master it works fine because there is no conflict. But when I'm trying to use Ansible like git: repo=xxxx dest=xxx version={{branch}} I got error: Local modifications exist in repository (force=no) If I add force=yes , then I will lose my local modifications. What can I do to keep my local changes and pull latest commit from git by using Ansible git module.
|
How to use Ansible git module pull a branch with local changes? My git workspace is dirty, there are some local modifications. When I use command git pull origin master it works fine because there is no conflict. But when I'm trying to use Ansible like git: repo=xxxx dest=xxx version={{branch}} I got error: Local modifications exist in repository (force=no) If I add force=yes , then I will lose my local modifications. What can I do to keep my local changes and pull latest commit from git by using Ansible git module.
|
git, ansible, devops
| 17
| 20,965
| 5
|
https://stackoverflow.com/questions/41178361/how-to-use-ansible-git-module-pull-a-branch-with-local-changes
|
49,755,521
|
ANSIBLE0013 Use shell only when shell functionality is required
|
In a Ansible role, I do this: - name: update trusted ca shell: "{{ in_ca_dict[ansible_os_family]['update']['shell'] }}" with: package_name: ca-certificates RedHat: path: 6: /usr/local/share/ca-certificates 7: /etc/pki/ca-trust/source/anchors update: shell: /bin/update-ca-trust Debian: path: /usr/local/share/ca-certificates update: shell: /usr/sbin/update-ca-certificates cache: "no" but ansible-lint tells me through molecule : [ANSIBLE0013] Use shell only when shell functionality is required When should shell functionality is required and when is it not required ? How should be the alternate way, my code seems fine to me.
|
ANSIBLE0013 Use shell only when shell functionality is required In a Ansible role, I do this: - name: update trusted ca shell: "{{ in_ca_dict[ansible_os_family]['update']['shell'] }}" with: package_name: ca-certificates RedHat: path: 6: /usr/local/share/ca-certificates 7: /etc/pki/ca-trust/source/anchors update: shell: /bin/update-ca-trust Debian: path: /usr/local/share/ca-certificates update: shell: /usr/sbin/update-ca-certificates cache: "no" but ansible-lint tells me through molecule : [ANSIBLE0013] Use shell only when shell functionality is required When should shell functionality is required and when is it not required ? How should be the alternate way, my code seems fine to me.
|
ansible, ansible-lint
| 17
| 11,658
| 1
|
https://stackoverflow.com/questions/49755521/ansible0013-use-shell-only-when-shell-functionality-is-required
|
24,625,539
|
Ansible 1.6 include with_items deprecated
|
So looks like this feature has been deprecated, i really don't understand why, Ansible CTO's says that we should use instead with_nested but honestly i have no idea how to do it, Here's my playboook: - hosts: all user: root vars: - sites: - site: site1.com repo: ssh://hg@bitbucket.org/orgname/reponame nginx_ssl: true; copy_init: - path1/file1.txt - path2/file2.php - path2/file3.php - site: site2.net repo: ssh://hg@bitbucket.org/orgname/reposite2 - site: site4.com repo: ssh://hg@bitbucket.org/orgname/reposite3 copy_init: - path2/file2.php tasks: - name: Bootstrap Sites include: bootstrap_site.yml site={{item}} And the error message when trying to execute this in Ansible 1.6.6: ERROR: [DEPRECATED]: include + with_items is a removed deprecated feature. Please update your playbooks. How can i convert this playbook to something that works with this ansible version?
|
Ansible 1.6 include with_items deprecated So looks like this feature has been deprecated, i really don't understand why, Ansible CTO's says that we should use instead with_nested but honestly i have no idea how to do it, Here's my playboook: - hosts: all user: root vars: - sites: - site: site1.com repo: ssh://hg@bitbucket.org/orgname/reponame nginx_ssl: true; copy_init: - path1/file1.txt - path2/file2.php - path2/file3.php - site: site2.net repo: ssh://hg@bitbucket.org/orgname/reposite2 - site: site4.com repo: ssh://hg@bitbucket.org/orgname/reposite3 copy_init: - path2/file2.php tasks: - name: Bootstrap Sites include: bootstrap_site.yml site={{item}} And the error message when trying to execute this in Ansible 1.6.6: ERROR: [DEPRECATED]: include + with_items is a removed deprecated feature. Please update your playbooks. How can i convert this playbook to something that works with this ansible version?
|
deprecated, ansible
| 17
| 14,676
| 2
|
https://stackoverflow.com/questions/24625539/ansible-1-6-include-with-items-deprecated
|
41,286,160
|
Can I use Jinja2 map filter in an Ansible play to get values from an array of objects?
|
I have a playbook for creating some EC2 instances and then doing some stuff with them. The relevant pieces are approximately like: - name: create ec2 instances ec2: id: '{{ item.name }}' instance_type: '{{ item.type }}' register: ec2 with_items: '{{ my_instance_defs }}' - name: wait for SSH wait_for: host: '{{ item.instances[0].private_ip }}' port: 22 with_items: '{{ ec2.results }}' This works as intended, but I am not especially happy with the item.instances[0].private_ip expression, partly because it shows really large objects in the play summary. I would love to have the with_items part just be an array of IP addresses, rather than an array of objects with arrays of objects inside them. In Python, I would just do something like: ips = [r['instances'][0]['private_ip'] for r in ec2['results']] And then I would use with_items: '{{ ips }}' in the second task. Is there a way I can do the same thing using a J2 filter in the YAML of the play? Seems like [URL] might be helpful, but I think that presupposes I have an array of keys/indices/whatever.
|
Can I use Jinja2 map filter in an Ansible play to get values from an array of objects? I have a playbook for creating some EC2 instances and then doing some stuff with them. The relevant pieces are approximately like: - name: create ec2 instances ec2: id: '{{ item.name }}' instance_type: '{{ item.type }}' register: ec2 with_items: '{{ my_instance_defs }}' - name: wait for SSH wait_for: host: '{{ item.instances[0].private_ip }}' port: 22 with_items: '{{ ec2.results }}' This works as intended, but I am not especially happy with the item.instances[0].private_ip expression, partly because it shows really large objects in the play summary. I would love to have the with_items part just be an array of IP addresses, rather than an array of objects with arrays of objects inside them. In Python, I would just do something like: ips = [r['instances'][0]['private_ip'] for r in ec2['results']] And then I would use with_items: '{{ ips }}' in the second task. Is there a way I can do the same thing using a J2 filter in the YAML of the play? Seems like [URL] might be helpful, but I think that presupposes I have an array of keys/indices/whatever.
|
ansible, jinja2
| 17
| 34,439
| 2
|
https://stackoverflow.com/questions/41286160/can-i-use-jinja2-map-filter-in-an-ansible-play-to-get-values-from-an-array-of
|
32,274,332
|
How to configure UFW reject policy in ansible without being disconnected?
|
I'm trying to configure UFW in Ansible like this: - name: Set firewall default policy ufw: state=enabled policy=reject sudo: true - name: Allow SSH in UFW ufw: rule=allow port=22 proto=tcp The problem is that as soon as the "Set firewall default policy" is executed ansible drops the connection to the server: TASK: [Set firewall default policy] ******************************************* changed: [xxx] TASK: [Allow SSH in UFW] ****************************************************** fatal: [xxx] => {'msg': 'FAILED: [Errno 61] Connection refused', 'failed': True} FATAL: all hosts have already failed -- aborting To me it looks like the SSH session is terminated when the reject policy has been applied. How do I solve this? I'm logging in with username/password authentication (i.e. no SSH key) if that makes any difference.
|
How to configure UFW reject policy in ansible without being disconnected? I'm trying to configure UFW in Ansible like this: - name: Set firewall default policy ufw: state=enabled policy=reject sudo: true - name: Allow SSH in UFW ufw: rule=allow port=22 proto=tcp The problem is that as soon as the "Set firewall default policy" is executed ansible drops the connection to the server: TASK: [Set firewall default policy] ******************************************* changed: [xxx] TASK: [Allow SSH in UFW] ****************************************************** fatal: [xxx] => {'msg': 'FAILED: [Errno 61] Connection refused', 'failed': True} FATAL: all hosts have already failed -- aborting To me it looks like the SSH session is terminated when the reject policy has been applied. How do I solve this? I'm logging in with username/password authentication (i.e. no SSH key) if that makes any difference.
|
ansible, ufw
| 17
| 9,574
| 2
|
https://stackoverflow.com/questions/32274332/how-to-configure-ufw-reject-policy-in-ansible-without-being-disconnected
|
51,622,712
|
Ansible requires python-apt but it's already installed
|
Prologue : I am just moving first stesp in ansible, so please be patient Also: I read the answers at 'Ansible demands installing MySQL-python despite it was already installed' but my case is different because locally, on the control machine, is all perfect; thanks to this question I discovered that my problem was in the remote controlled machine. So my questions is the same but the question linked do not contains an answer to resolve my problem . I'm testing ansible from command line. For example, I succesfully can ping ~/.ssh$ ansible openvpn -C -m "ping" 192.168.1.225 | SUCCESS => { "changed": false, "ping": "pong" } I tried to launch an apt update . I am not sure if this is the right syntax for having the equivalent of apt-get update , but this is not the question I am using -C to see what ansible says to me when I ask to do a dry run. $ ansible openvpn -C -m "apt update-cache=yes" 192.168.1.225 | FAILED! => { "changed": false, "msg": "python-apt must be installed to use check mode. If run normally this module can auto-install it." } EDIT : As @Davide Maze suggested, it could be due to missing python-apt . So I checked, but _I have python-apt $ python -V Python 2.7.15rc1 $ pip list ... cut ... python-apt (1.6.2) ... cut ... $ which python /usr/bin/python My question is: why does ansible tell me that python-apt is not installed, and how to fix this?
|
Ansible requires python-apt but it's already installed Prologue : I am just moving first stesp in ansible, so please be patient Also: I read the answers at 'Ansible demands installing MySQL-python despite it was already installed' but my case is different because locally, on the control machine, is all perfect; thanks to this question I discovered that my problem was in the remote controlled machine. So my questions is the same but the question linked do not contains an answer to resolve my problem . I'm testing ansible from command line. For example, I succesfully can ping ~/.ssh$ ansible openvpn -C -m "ping" 192.168.1.225 | SUCCESS => { "changed": false, "ping": "pong" } I tried to launch an apt update . I am not sure if this is the right syntax for having the equivalent of apt-get update , but this is not the question I am using -C to see what ansible says to me when I ask to do a dry run. $ ansible openvpn -C -m "apt update-cache=yes" 192.168.1.225 | FAILED! => { "changed": false, "msg": "python-apt must be installed to use check mode. If run normally this module can auto-install it." } EDIT : As @Davide Maze suggested, it could be due to missing python-apt . So I checked, but _I have python-apt $ python -V Python 2.7.15rc1 $ pip list ... cut ... python-apt (1.6.2) ... cut ... $ which python /usr/bin/python My question is: why does ansible tell me that python-apt is not installed, and how to fix this?
|
python, ansible
| 17
| 35,781
| 2
|
https://stackoverflow.com/questions/51622712/ansible-requires-python-apt-but-its-already-installed
|
50,477,012
|
How to use a dictionary of registered ansible variables in vars?
|
I want to pass multiple variables to a task using vars . Currently, I am doing it like below vars: var1_name: "var1_value" var2_name: "var2_value" As the number of variables can grow in size, I'd rather prefer to pass the dictionary of variables to the task using vars . I have constructed a dictionary of variables like below - name: set fact hosts: localhost tasks: - set_fact: variables: "{{ variables|default({}) | combine( {item.variable: item.value} ) }}" with_items: - variable: var1_name value: "var1_value" - variable: var2_name value: "var2_name" Dictionary looks something like this: "variables": { "var1_name": "var1_value", "var2_name": "var2_value", } Now, I want to make variables in this dictionary available to roles executing on other hosts. But, when I tried to pass dictionary to vars like below vars: "{{ variables }}" Ansible throws the error: ERROR! Vars in a Play must be specified as a dictionary, or a list of dictionaries How to pass a dictionary variable in vars ?
|
How to use a dictionary of registered ansible variables in vars? I want to pass multiple variables to a task using vars . Currently, I am doing it like below vars: var1_name: "var1_value" var2_name: "var2_value" As the number of variables can grow in size, I'd rather prefer to pass the dictionary of variables to the task using vars . I have constructed a dictionary of variables like below - name: set fact hosts: localhost tasks: - set_fact: variables: "{{ variables|default({}) | combine( {item.variable: item.value} ) }}" with_items: - variable: var1_name value: "var1_value" - variable: var2_name value: "var2_name" Dictionary looks something like this: "variables": { "var1_name": "var1_value", "var2_name": "var2_value", } Now, I want to make variables in this dictionary available to roles executing on other hosts. But, when I tried to pass dictionary to vars like below vars: "{{ variables }}" Ansible throws the error: ERROR! Vars in a Play must be specified as a dictionary, or a list of dictionaries How to pass a dictionary variable in vars ?
|
ansible, yaml, ansible-facts
| 17
| 23,459
| 2
|
https://stackoverflow.com/questions/50477012/how-to-use-a-dictionary-of-registered-ansible-variables-in-vars
|
42,170,515
|
Using the first host in group
|
My ansible host definition looks like [elasticclient] 192.168.10.2 192.168.10.3 I want to use the first host in the group to be used in a variable. My playbook is - hosts: kibana roles: - kibana vars: kibana_elasticsearch_url: [URL] groups[['elasticclient'][0]] }}:9200 When I run this, my file contains [URL] How do I change it to [URL]
|
Using the first host in group My ansible host definition looks like [elasticclient] 192.168.10.2 192.168.10.3 I want to use the first host in the group to be used in a variable. My playbook is - hosts: kibana roles: - kibana vars: kibana_elasticsearch_url: [URL] groups[['elasticclient'][0]] }}:9200 When I run this, my file contains [URL] How do I change it to [URL]
|
ansible
| 17
| 25,662
| 3
|
https://stackoverflow.com/questions/42170515/using-the-first-host-in-group
|
41,774,695
|
Ansible ec2: "boto required for this module"
|
When I run this simple Ansible playbook: - name: EC2 Test Example hosts: localhost connection: local gather_facts: False tasks: - name: EC2 Instance ec2: # Amazon EC2 key pair name key_name: my-key-pair # Amazon EC2 Security Group group: my-security-group instance_type: t2.micro # Latest from [URL] image: ami-221ea342 wait: yes register: ec2 I run with venv/bin/ansible-playbook -i localhost, playbook.yml : PLAY [EC2 Test Example] ******************************************************** TASK [EC2 Instance] ************************************************************ fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "boto required for this module"} to retry, use: --limit @/Users/admin/temp/ansec2/playbook.retry PLAY RECAP ********************************************************************* localhost : ok=0 changed=0 unreachable=0 failed=1 So obviously, I have boto installed in the venv that I'm using as well as my default system Python: β ansec2 venv/bin/pip list Package Version --------------- -------- ansible 2.2.1.0 boto 2.45.0 boto3 1.4.4 botocore 1.5.4 ... I've read a few similar posts and I don't see a working solution.
|
Ansible ec2: "boto required for this module" When I run this simple Ansible playbook: - name: EC2 Test Example hosts: localhost connection: local gather_facts: False tasks: - name: EC2 Instance ec2: # Amazon EC2 key pair name key_name: my-key-pair # Amazon EC2 Security Group group: my-security-group instance_type: t2.micro # Latest from [URL] image: ami-221ea342 wait: yes register: ec2 I run with venv/bin/ansible-playbook -i localhost, playbook.yml : PLAY [EC2 Test Example] ******************************************************** TASK [EC2 Instance] ************************************************************ fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "boto required for this module"} to retry, use: --limit @/Users/admin/temp/ansec2/playbook.retry PLAY RECAP ********************************************************************* localhost : ok=0 changed=0 unreachable=0 failed=1 So obviously, I have boto installed in the venv that I'm using as well as my default system Python: β ansec2 venv/bin/pip list Package Version --------------- -------- ansible 2.2.1.0 boto 2.45.0 boto3 1.4.4 botocore 1.5.4 ... I've read a few similar posts and I don't see a working solution.
|
ansible, boto
| 17
| 26,008
| 3
|
https://stackoverflow.com/questions/41774695/ansible-ec2-boto-required-for-this-module
|
29,026,094
|
Ansible: Access host/group vars from within custom module
|
Is there a way how one can access host/group vars from within a custom written module ? I would like to avoid to pass all required vars as module parameters. My module is written in Python and I use the boilerplate. I checked pretty much all available vars but they are not stored anywhere: def main(): pprint(dir()) pprint(globals()) pprint(locals()) for name in vars().keys(): print(name) Now my only hope is they are somehow accessible through the undocumented module utils. I guess it is not possible, since the module runs on the target machine and probably the facts/host/group vars are not transferred along with the module... Edit: Found the module utils now and it doesn't look promising.
|
Ansible: Access host/group vars from within custom module Is there a way how one can access host/group vars from within a custom written module ? I would like to avoid to pass all required vars as module parameters. My module is written in Python and I use the boilerplate. I checked pretty much all available vars but they are not stored anywhere: def main(): pprint(dir()) pprint(globals()) pprint(locals()) for name in vars().keys(): print(name) Now my only hope is they are somehow accessible through the undocumented module utils. I guess it is not possible, since the module runs on the target machine and probably the facts/host/group vars are not transferred along with the module... Edit: Found the module utils now and it doesn't look promising.
|
python, ansible
| 17
| 6,025
| 3
|
https://stackoverflow.com/questions/29026094/ansible-access-host-group-vars-from-within-custom-module
|
33,155,459
|
Ansible: how to run a play with hosts with different passwords?
|
I'm currently learning how to use Ansible. Right now, I've got a bunch of servers, both new and legacy, that have different logins or passwords or both. All have key access to run the plays. Here's what I started with. Example hosts file: # legacy and new have different logins (like root and deploy) [legacy] serv1 serv2 [new] serv3 serv4 # different has a different login and password altogether [different] serv5 So to keep things simple, I originally had a playbook run the equivalent of sudo apt-get update && sudo apt-get upgrade on all the machines, but because of the different login/passwd, I had created multiple playbooks for each host. But now I want to DRY it out and am looking at Roles, per their docs. Right now I have something like this. The test/roles/common/tasks/main.yml file: --- - name: run apt-get update apt: update_cache=yes - name: run apt-get upgrade apt: upgrade=yes The site.yml file: - name: apply common configuration to all nodes hosts: all roles: - common I understand that I can actually define the different logins with ansible_ssh_user=root or ...=deploy in my hosts file. Or put them in group vars. But what do I do about the different sudo passwords? [legacy] is root so I don't need sudo , but [new] and [different] need it, and have different passwords. How do I do this? Group vars? Do I create these: test/group_vars/new/some_file_with_a_passwd.yml and test/group_vars/different/some_other_passwd.yml (ignoring security issues)? How does the site.yml recognize that there are hosts with different passwords or some hosts with no passwords? Edit for clarity's sake: I have SSH access, so doing the 'pre-tasks' step during the play always work (I connect via key access and never via a password). I'm not worried about security as that's the next step. For now, I want to get the group_vars thing right....It's the sudo escalation I have issues with. E.g. serv1 sudo might be root/password1, serv3 sudo: deploy/password2, serv5: anotherdeploy/password3
|
Ansible: how to run a play with hosts with different passwords? I'm currently learning how to use Ansible. Right now, I've got a bunch of servers, both new and legacy, that have different logins or passwords or both. All have key access to run the plays. Here's what I started with. Example hosts file: # legacy and new have different logins (like root and deploy) [legacy] serv1 serv2 [new] serv3 serv4 # different has a different login and password altogether [different] serv5 So to keep things simple, I originally had a playbook run the equivalent of sudo apt-get update && sudo apt-get upgrade on all the machines, but because of the different login/passwd, I had created multiple playbooks for each host. But now I want to DRY it out and am looking at Roles, per their docs. Right now I have something like this. The test/roles/common/tasks/main.yml file: --- - name: run apt-get update apt: update_cache=yes - name: run apt-get upgrade apt: upgrade=yes The site.yml file: - name: apply common configuration to all nodes hosts: all roles: - common I understand that I can actually define the different logins with ansible_ssh_user=root or ...=deploy in my hosts file. Or put them in group vars. But what do I do about the different sudo passwords? [legacy] is root so I don't need sudo , but [new] and [different] need it, and have different passwords. How do I do this? Group vars? Do I create these: test/group_vars/new/some_file_with_a_passwd.yml and test/group_vars/different/some_other_passwd.yml (ignoring security issues)? How does the site.yml recognize that there are hosts with different passwords or some hosts with no passwords? Edit for clarity's sake: I have SSH access, so doing the 'pre-tasks' step during the play always work (I connect via key access and never via a password). I'm not worried about security as that's the next step. For now, I want to get the group_vars thing right....It's the sudo escalation I have issues with. E.g. serv1 sudo might be root/password1, serv3 sudo: deploy/password2, serv5: anotherdeploy/password3
|
ubuntu, roles, ansible
| 17
| 28,215
| 3
|
https://stackoverflow.com/questions/33155459/ansible-how-to-run-a-play-with-hosts-with-different-passwords
|
33,672,491
|
How to use ansible to provision vim vundle plugin?
|
I use vundle as plugin manager for vim. And I want to use ansible to automate vundle plugin installation. But I just can't get ansible to do provision automatically: - name: install vundle plugin shell: vim +PluginInstall +qall above is the ansible playbook YML file for vim. When ansible start to run this task, it just goes on forever, it never ends and it never fails. Until I force it to stop by CTRL C . If I run that command directly in the guest os, it works fine, vim shows up and finishes installation. What's the problem here? ========================================== Edit: After read Roy Zuo 's answer, and turn on verbose mode of vim, I tried the following command: vim -E -s -c "source ~/.vimrc" +PluginInstall +qall -V and below is the output: continuing in /home/vagrant/.vimrc Searching for "/usr/share/vim/vimfiles/after/syntax/syncolor.vim" Searching for "/home/vagrant/.vim/after/syntax/syncolor.vim" Searching for "/home/vagrant/.vim/bundle/Vundle.vim/syntax/syncolor.vim" Searching for "/after/syntax/syncolor.vim" Searching for "colors/solarized.vim" in "/home/vagrant/.vim,/usr/share/vim/vimfiles,/usr/share/vim/vim74,/usr/share/vim/vimfiles/after,/home/vagrant/.vim/after,/home/vagrant/.vim/bundle/Vundle.vim,/after" Searching for "/home/vagrant/.vim/colors/solarized.vim" Searching for "/usr/share/vim/vimfiles/colors/solarized.vim" Searching for "/usr/share/vim/vim74/colors/solarized.vim" Searching for "/usr/share/vim/vimfiles/after/colors/solarized.vim" Searching for "/home/vagrant/.vim/after/colors/solarized.vim" Searching for "/home/vagrant/.vim/bundle/Vundle.vim/colors/solarized.vim" Searching for "/after/colors/solarized.vim" not found in 'runtimepath': "colors/solarized.vim" line 188: E185: Cannot find color scheme 'solarized' finished sourcing /home/vagrant/.vimrc continuing in command line It seems vim stopped when it can't find the plugin specified in .vimrc. Any idea how to continue?
|
How to use ansible to provision vim vundle plugin? I use vundle as plugin manager for vim. And I want to use ansible to automate vundle plugin installation. But I just can't get ansible to do provision automatically: - name: install vundle plugin shell: vim +PluginInstall +qall above is the ansible playbook YML file for vim. When ansible start to run this task, it just goes on forever, it never ends and it never fails. Until I force it to stop by CTRL C . If I run that command directly in the guest os, it works fine, vim shows up and finishes installation. What's the problem here? ========================================== Edit: After read Roy Zuo 's answer, and turn on verbose mode of vim, I tried the following command: vim -E -s -c "source ~/.vimrc" +PluginInstall +qall -V and below is the output: continuing in /home/vagrant/.vimrc Searching for "/usr/share/vim/vimfiles/after/syntax/syncolor.vim" Searching for "/home/vagrant/.vim/after/syntax/syncolor.vim" Searching for "/home/vagrant/.vim/bundle/Vundle.vim/syntax/syncolor.vim" Searching for "/after/syntax/syncolor.vim" Searching for "colors/solarized.vim" in "/home/vagrant/.vim,/usr/share/vim/vimfiles,/usr/share/vim/vim74,/usr/share/vim/vimfiles/after,/home/vagrant/.vim/after,/home/vagrant/.vim/bundle/Vundle.vim,/after" Searching for "/home/vagrant/.vim/colors/solarized.vim" Searching for "/usr/share/vim/vimfiles/colors/solarized.vim" Searching for "/usr/share/vim/vim74/colors/solarized.vim" Searching for "/usr/share/vim/vimfiles/after/colors/solarized.vim" Searching for "/home/vagrant/.vim/after/colors/solarized.vim" Searching for "/home/vagrant/.vim/bundle/Vundle.vim/colors/solarized.vim" Searching for "/after/colors/solarized.vim" not found in 'runtimepath': "colors/solarized.vim" line 188: E185: Cannot find color scheme 'solarized' finished sourcing /home/vagrant/.vimrc continuing in command line It seems vim stopped when it can't find the plugin specified in .vimrc. Any idea how to continue?
|
vim, ansible, vundle
| 17
| 3,477
| 3
|
https://stackoverflow.com/questions/33672491/how-to-use-ansible-to-provision-vim-vundle-plugin
|
52,438,350
|
How to overwrite file in Ansible
|
I want to ovrwrite file on remote location using Ansible. No matter content in zip file is changes or not, everytime I run playbook file needs to be overwrite on destination server. Below is my playbook - hosts: localhost tasks: - name: Checking if File is exsists to copy to update servers. stat: path: "/var/lib/abc.zip" get_checksum: False get_md5: False register: win_stat_result - debug: var: win_stat_result.stat.exists - hosts: uploads tasks: - name: Getting VARs debug: var: hostvars['localhost']['win_stat_result']['stat'] ['exists'] - name: copy Files to Destination Servers win_copy: src: "/var/lib/abc.zip" dest: E:\xyz\data\charts.zip force: yes when: hostvars['localhost']['win_stat_result']['stat']['exists'] When I run this playbook it didn't overwrite file on destination as file is already exists. I used force=yes but it didn't worked.
|
How to overwrite file in Ansible I want to ovrwrite file on remote location using Ansible. No matter content in zip file is changes or not, everytime I run playbook file needs to be overwrite on destination server. Below is my playbook - hosts: localhost tasks: - name: Checking if File is exsists to copy to update servers. stat: path: "/var/lib/abc.zip" get_checksum: False get_md5: False register: win_stat_result - debug: var: win_stat_result.stat.exists - hosts: uploads tasks: - name: Getting VARs debug: var: hostvars['localhost']['win_stat_result']['stat'] ['exists'] - name: copy Files to Destination Servers win_copy: src: "/var/lib/abc.zip" dest: E:\xyz\data\charts.zip force: yes when: hostvars['localhost']['win_stat_result']['stat']['exists'] When I run this playbook it didn't overwrite file on destination as file is already exists. I used force=yes but it didn't worked.
|
ansible
| 17
| 56,286
| 3
|
https://stackoverflow.com/questions/52438350/how-to-overwrite-file-in-ansible
|
50,031,257
|
ansible: promoting warnings to errors
|
I have some continuous integration checks which run a few ansible-playbook commands. Each playbook may be running many plays, including numerous large roles. Every now and then, somebody introduces some change that causes a warning when ansible-playbook runs, e.g. something like this: [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: "{{ some_variable}}" not in some_result.stdout or: [WARNING]: Consider using unarchive module rather than running tar or some deprecation warnings like: [DEPRECATION WARNING]: ec2_facts is kept for backwards compatibility but usage is discouraged. The module documentation details page may explain more about this rationale.. This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. and so on. Sometimes these warnings pop up when we upgrade ansible versions. Regardless of why they happen, I would really like for some way to have the ansible-playbook command fail loudly when it causes one of these warnings, instead of quietly proceeding on and having my CI check be successful. Is there any way to do this? I'm using ansible 2.4.3 currently. I find lots of discussion about ways to hide these warnings, but haven't found anything about promoting them to hard errors.
|
ansible: promoting warnings to errors I have some continuous integration checks which run a few ansible-playbook commands. Each playbook may be running many plays, including numerous large roles. Every now and then, somebody introduces some change that causes a warning when ansible-playbook runs, e.g. something like this: [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: "{{ some_variable}}" not in some_result.stdout or: [WARNING]: Consider using unarchive module rather than running tar or some deprecation warnings like: [DEPRECATION WARNING]: ec2_facts is kept for backwards compatibility but usage is discouraged. The module documentation details page may explain more about this rationale.. This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. and so on. Sometimes these warnings pop up when we upgrade ansible versions. Regardless of why they happen, I would really like for some way to have the ansible-playbook command fail loudly when it causes one of these warnings, instead of quietly proceeding on and having my CI check be successful. Is there any way to do this? I'm using ansible 2.4.3 currently. I find lots of discussion about ways to hide these warnings, but haven't found anything about promoting them to hard errors.
|
ansible, warnings
| 17
| 6,330
| 4
|
https://stackoverflow.com/questions/50031257/ansible-promoting-warnings-to-errors
|
25,977,410
|
adding an fstab option using Ansible
|
I am trying to add nodev to my /etc/fstab file. I am using the Ansible command below but with no luck. My issue lies with the regular expression, I'm not a pro at regex. - name: Add nodev to /etc/fstab lineinfile: dest=/etc/fstab backup=yes backrefs=yes state=present regexp='(^/dev[\w/_-]+(\s+(?!nodev)[\w,]+)*)' line='\1,nodev' One of the lines from /etc/fstab that I am trying to add nodev is: /dev/mapper/ex_sys-ex_home /home /ext4 rw,exec,auto,nouser,sync 1 2
|
adding an fstab option using Ansible I am trying to add nodev to my /etc/fstab file. I am using the Ansible command below but with no luck. My issue lies with the regular expression, I'm not a pro at regex. - name: Add nodev to /etc/fstab lineinfile: dest=/etc/fstab backup=yes backrefs=yes state=present regexp='(^/dev[\w/_-]+(\s+(?!nodev)[\w,]+)*)' line='\1,nodev' One of the lines from /etc/fstab that I am trying to add nodev is: /dev/mapper/ex_sys-ex_home /home /ext4 rw,exec,auto,nouser,sync 1 2
|
regex, ansible, mount, mount-point
| 16
| 46,228
| 7
|
https://stackoverflow.com/questions/25977410/adding-an-fstab-option-using-ansible
|
54,258,289
|
ansible: 'default' filter that treats the empty string as not defined
|
If I do this: - set_fact: NEW_VARIABLE: "{{ VARIABLE | default('default') }}" and VARIABLE is the empty string ( "" ), than the default not triggering. I could do this: - set_fact: NEW_VARIABLE: "{{ VARIABLE | default('default') }}" - set_fact: NEW_VARIABLE: "default" when: VARIABLE == "" But I actually want to do this in a loop. So it would be much easier if I could do this using ansible filters and not conditionals. Is this possible? Are there ansible filters that work like default but treats "" as not defined?
|
ansible: 'default' filter that treats the empty string as not defined If I do this: - set_fact: NEW_VARIABLE: "{{ VARIABLE | default('default') }}" and VARIABLE is the empty string ( "" ), than the default not triggering. I could do this: - set_fact: NEW_VARIABLE: "{{ VARIABLE | default('default') }}" - set_fact: NEW_VARIABLE: "default" when: VARIABLE == "" But I actually want to do this in a loop. So it would be much easier if I could do this using ansible filters and not conditionals. Is this possible? Are there ansible filters that work like default but treats "" as not defined?
|
ansible
| 16
| 27,919
| 2
|
https://stackoverflow.com/questions/54258289/ansible-default-filter-that-treats-the-empty-string-as-not-defined
|
56,350,113
|
Ansible: Create a Self-Signed SSL Certificate and Key
|
I want to create a self signed certificate to use it with stunnel, in order to securely tunnel my redis traffic between the redis server and client. I'm using this command to generate the certificate and it works fine. openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/stunnel/redis-server.key -out /etc/stunnel/redis-server.crt Since I'm using Ansible for provisioning, I would like to know how I can convert this into a more Ansible way of doing, using a module. There actually is a module called the openssl_certificate Ansible module and it states "This module allows one to (re)generate OpenSSL certificates." . I tried to use the module to generate the certificate, but I couldn't get it to work. - name: Generate a Self Signed OpenSSL certificate openssl_certificate: path: /etc/stunnel/redis-server.crt privatekey_path: /etc/stunnel/redis-server.key csr_path: /etc/stunnel/redis-server.csr provider: selfsigned From a look at the documentation, I can't specify the following arguments -x509 -nodes -days 3650 -newkey rsa:2048 . Of course, I could also split the key and cert generation, but that still wouldn't allow me to use the Ansible module, correct? Example given: openssl genrsa -out /etc/stunnel/key.pem 4096 openssl req -new -x509 -key /etc/stunnel/key.pem -out /etc/stunnel/cert.pem -days 1826 I would like to know the following things: a) How can I get the same result from the original command, but using an Ansible module? b) Is there a better way to manage self signed certificates using Ansible?
|
Ansible: Create a Self-Signed SSL Certificate and Key I want to create a self signed certificate to use it with stunnel, in order to securely tunnel my redis traffic between the redis server and client. I'm using this command to generate the certificate and it works fine. openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/stunnel/redis-server.key -out /etc/stunnel/redis-server.crt Since I'm using Ansible for provisioning, I would like to know how I can convert this into a more Ansible way of doing, using a module. There actually is a module called the openssl_certificate Ansible module and it states "This module allows one to (re)generate OpenSSL certificates." . I tried to use the module to generate the certificate, but I couldn't get it to work. - name: Generate a Self Signed OpenSSL certificate openssl_certificate: path: /etc/stunnel/redis-server.crt privatekey_path: /etc/stunnel/redis-server.key csr_path: /etc/stunnel/redis-server.csr provider: selfsigned From a look at the documentation, I can't specify the following arguments -x509 -nodes -days 3650 -newkey rsa:2048 . Of course, I could also split the key and cert generation, but that still wouldn't allow me to use the Ansible module, correct? Example given: openssl genrsa -out /etc/stunnel/key.pem 4096 openssl req -new -x509 -key /etc/stunnel/key.pem -out /etc/stunnel/cert.pem -days 1826 I would like to know the following things: a) How can I get the same result from the original command, but using an Ansible module? b) Is there a better way to manage self signed certificates using Ansible?
|
ssl, openssl, ansible
| 16
| 22,262
| 3
|
https://stackoverflow.com/questions/56350113/ansible-create-a-self-signed-ssl-certificate-and-key
|
42,038,633
|
Ansible Yum Module pending transactions error
|
I'm very new to Ansible. I am trying to follow a tutorial on the concept of Roles in Ansible. I have the following Master Playbook: --- # Master Playbook for Webservers - hosts: apacheweb user: test sudo: yes connection: ssh roles: - webservers Which refers to the webservers role that has the following task/main.yml : - name: Install Apache Web Server yum: pkg=httpd state=latest notify: Restart HTTPD And a handler/main.yml : - name: Restart HTTPD service: name=httpd state=started When I execute the Master Playbook, mentioned above, I get the following error: TASK [webservers : Install Apache Web Server] ********************************** fatal: [test.server.com]: FAILED! => {"changed": false, "failed": true, "msg": "The following packages have pending transactions: httpd-x86_64", "rc": 128, "results": ["The following packages have pending transactions: httpd-x86_64"]} I cannot understand what this error corresponds to. There does not seem to be anything similar, based on my research, that could suggest the issue with the way I am using the Yum module. NOTE: Ansible Version: ansible 2.2.1.0 config file = /etc/ansible/ansible.cfg
|
Ansible Yum Module pending transactions error I'm very new to Ansible. I am trying to follow a tutorial on the concept of Roles in Ansible. I have the following Master Playbook: --- # Master Playbook for Webservers - hosts: apacheweb user: test sudo: yes connection: ssh roles: - webservers Which refers to the webservers role that has the following task/main.yml : - name: Install Apache Web Server yum: pkg=httpd state=latest notify: Restart HTTPD And a handler/main.yml : - name: Restart HTTPD service: name=httpd state=started When I execute the Master Playbook, mentioned above, I get the following error: TASK [webservers : Install Apache Web Server] ********************************** fatal: [test.server.com]: FAILED! => {"changed": false, "failed": true, "msg": "The following packages have pending transactions: httpd-x86_64", "rc": 128, "results": ["The following packages have pending transactions: httpd-x86_64"]} I cannot understand what this error corresponds to. There does not seem to be anything similar, based on my research, that could suggest the issue with the way I am using the Yum module. NOTE: Ansible Version: ansible 2.2.1.0 config file = /etc/ansible/ansible.cfg
|
ansible, yum
| 16
| 16,543
| 3
|
https://stackoverflow.com/questions/42038633/ansible-yum-module-pending-transactions-error
|
53,976,165
|
Importing/adding a yum .repo file using Ansible
|
I'm trying to install MariaDB (or any software) from a custom repository using Ansible but I am not sure how to import the .repo file using the yum/ yum_repository modules. Ansible Here is my playbook: - hosts: all become: true remote_user: root tasks: - name: set system timezone timezone: name: America/Toronto - name: add custom repository yum_repository: name: centos_o description: custom repositories baseurl: [URL] - name: ensure mariadb is installed yum: name: mariadb-server-5.5.* state: installed I've tried all include , metalink , baseurl , and mirrorlist with no luck. Also I am missing the GPG key step, but I can't even get the repo added properly. The centos_o.repo file looks like this: # JENKINS [jenkins] name=CentOS-$releasever - JENKINS baseurl=[URL] enabled=0 gpgcheck=1 # MariaDB 5.5 [mariadb] name=CentOS-$releasever - MariaDB baseurl=[URL] enabled=0 gpgcheck=1 # MariaDB 10.0 [mariadb] name=CentOS-$releasever - MariaDB baseurl=[URL] enabled=0 gpgcheck=1 Shell This is the shell script version that I am trying to convert to Ansible: yum clean all yum-config-manager --add-repo=[URL] yum-config-manager --enable mariadb rpm --import [URL] If it makes any difference, I am running this with Vagrant's Ansible local provisioner on a CentOS box.
|
Importing/adding a yum .repo file using Ansible I'm trying to install MariaDB (or any software) from a custom repository using Ansible but I am not sure how to import the .repo file using the yum/ yum_repository modules. Ansible Here is my playbook: - hosts: all become: true remote_user: root tasks: - name: set system timezone timezone: name: America/Toronto - name: add custom repository yum_repository: name: centos_o description: custom repositories baseurl: [URL] - name: ensure mariadb is installed yum: name: mariadb-server-5.5.* state: installed I've tried all include , metalink , baseurl , and mirrorlist with no luck. Also I am missing the GPG key step, but I can't even get the repo added properly. The centos_o.repo file looks like this: # JENKINS [jenkins] name=CentOS-$releasever - JENKINS baseurl=[URL] enabled=0 gpgcheck=1 # MariaDB 5.5 [mariadb] name=CentOS-$releasever - MariaDB baseurl=[URL] enabled=0 gpgcheck=1 # MariaDB 10.0 [mariadb] name=CentOS-$releasever - MariaDB baseurl=[URL] enabled=0 gpgcheck=1 Shell This is the shell script version that I am trying to convert to Ansible: yum clean all yum-config-manager --add-repo=[URL] yum-config-manager --enable mariadb rpm --import [URL] If it makes any difference, I am running this with Vagrant's Ansible local provisioner on a CentOS box.
|
ansible, yum, vagrant-provision
| 16
| 28,048
| 2
|
https://stackoverflow.com/questions/53976165/importing-adding-a-yum-repo-file-using-ansible
|
34,949,595
|
How to delete *.web files only if they exist
|
I need to create an Ansible playbook to delete the *.web files in a specific directory only if the files exists. OS : cent OS, Redhat 5x, 6x. I have tried the following with no success: - stat: path=/opt/app/jboss/configuration/*.web register: web - shell: rm -rf /opt/app/jboss/configuration/*.web when: web.stat.exists
|
How to delete *.web files only if they exist I need to create an Ansible playbook to delete the *.web files in a specific directory only if the files exists. OS : cent OS, Redhat 5x, 6x. I have tried the following with no success: - stat: path=/opt/app/jboss/configuration/*.web register: web - shell: rm -rf /opt/app/jboss/configuration/*.web when: web.stat.exists
|
ansible
| 16
| 56,814
| 3
|
https://stackoverflow.com/questions/34949595/how-to-delete-web-files-only-if-they-exist
|
57,888,312
|
copy files to server from relative path in ansible
|
How can I pass a relative path so that Ansible can copy files from node/keys and copy them to a server? The playbook is ansible/playbook . My directory structure is: βββ ansible β βββ inventory β βββ playbook βββ node β βββ keys β βββ index.js β βββ node_modules β βββ package-lock.json β βββ utils βββ shell βββ data.json βββ create-data.sh βββ destory.sh βββ firewall-rules.sh Below is the playbook: - hosts: all vars: source: "{{ source }}" destination: /home/ubuntu tasks: - name: Copy files copy: src: "{{ source }}" dest: "{{ destination }}" That's how I run: ansible-playbook -i inventory/inventory.yaml playbook/crypto-generate.yaml --extra-vars "source=../node/keys" I am trying to pass a relative path.
|
copy files to server from relative path in ansible How can I pass a relative path so that Ansible can copy files from node/keys and copy them to a server? The playbook is ansible/playbook . My directory structure is: βββ ansible β βββ inventory β βββ playbook βββ node β βββ keys β βββ index.js β βββ node_modules β βββ package-lock.json β βββ utils βββ shell βββ data.json βββ create-data.sh βββ destory.sh βββ firewall-rules.sh Below is the playbook: - hosts: all vars: source: "{{ source }}" destination: /home/ubuntu tasks: - name: Copy files copy: src: "{{ source }}" dest: "{{ destination }}" That's how I run: ansible-playbook -i inventory/inventory.yaml playbook/crypto-generate.yaml --extra-vars "source=../node/keys" I am trying to pass a relative path.
|
ansible, ansible-inventory, ansible-facts
| 16
| 19,796
| 2
|
https://stackoverflow.com/questions/57888312/copy-files-to-server-from-relative-path-in-ansible
|
44,838,421
|
Ansible: Multiple and/or conditionals in when clause
|
I am having issues when trying to use multiple and/or conditionals in a when statement to decide whether a task needs to be ran or not. Basically I am making a playbook to do automated system patching with options for security patches, kernel only patches and to specify packages in a var file. I run the playbook with the following commands and define the variables through extended variables option (-e) ansible-playbook site.yml \ -i inventory \ --ask-vault \ -u (username) \ -e "security=true restart=true" \ -k -K By default the playbook will update every package on the system except kernel but I would like to skip that action if I specify any of a few variables. The code I have is the following: - name: Update all packages yum: name: "*" state: latest exclude: "kernel*" when: > security is not defined or kernel is not defined or specified_packages is not defined and ansible_os_family == "RedHat" I've tried all of the following combinations: when: (ansible_os_family == "RedHat") and (security is defined or kernel is defined or specified_packages is defined) # this case throws a not defined error because i don't define all variables every time i run the playbook when: (ansible_os_family == "RedHat") and (security == true or kernel == true or specified_packages == true ) when: ansible_os_family == "RedHat" when: security is defined or kernel is defined or specified_packages is defined Note: I am aware and have used an extra variable such as "skip" to skip this task and use the when clause when: ansible_os_family == "RedHat" and skip is not defined but would prefer not have my users need to use an extra variable just to skip this default action. I also am not using tags as I am gathering a list of packages before and after the upgrade to compare and report in the end so I wont be able to run those as they are local action commands. This is why I'm using one role with multiple tasks turned on and off via extended variables. I am open to any suggestion that rewrites the playbook in a more efficient way as I am sort of a noob.
|
Ansible: Multiple and/or conditionals in when clause I am having issues when trying to use multiple and/or conditionals in a when statement to decide whether a task needs to be ran or not. Basically I am making a playbook to do automated system patching with options for security patches, kernel only patches and to specify packages in a var file. I run the playbook with the following commands and define the variables through extended variables option (-e) ansible-playbook site.yml \ -i inventory \ --ask-vault \ -u (username) \ -e "security=true restart=true" \ -k -K By default the playbook will update every package on the system except kernel but I would like to skip that action if I specify any of a few variables. The code I have is the following: - name: Update all packages yum: name: "*" state: latest exclude: "kernel*" when: > security is not defined or kernel is not defined or specified_packages is not defined and ansible_os_family == "RedHat" I've tried all of the following combinations: when: (ansible_os_family == "RedHat") and (security is defined or kernel is defined or specified_packages is defined) # this case throws a not defined error because i don't define all variables every time i run the playbook when: (ansible_os_family == "RedHat") and (security == true or kernel == true or specified_packages == true ) when: ansible_os_family == "RedHat" when: security is defined or kernel is defined or specified_packages is defined Note: I am aware and have used an extra variable such as "skip" to skip this task and use the when clause when: ansible_os_family == "RedHat" and skip is not defined but would prefer not have my users need to use an extra variable just to skip this default action. I also am not using tags as I am gathering a list of packages before and after the upgrade to compare and report in the end so I wont be able to run those as they are local action commands. This is why I'm using one role with multiple tasks turned on and off via extended variables. I am open to any suggestion that rewrites the playbook in a more efficient way as I am sort of a noob.
|
ansible, ansible-2.x
| 16
| 107,323
| 3
|
https://stackoverflow.com/questions/44838421/ansible-multiple-and-or-conditionals-in-when-clause
|
38,795,908
|
how to select regex matches in jinja2?
|
toy example Essentially, I want to do something like: ['hello', 'apple', 'rare', 'trim', 'three'] | select(match('.*a[rp].*')) Which would yield: ['apple', 'rare'] what am I talking about? The match filter and select filter. My issue arises from the fact that the select filter only supports unary "tests". I'm on Ansible 1.9.x. my actual use case ...is closer to: lookup('dig', ip_address, qtype="PTR", wantList=True) | select(match("mx\\..*\\.example\\.com")) So, I want to get all the PTR records associated with an IP and then filter out all the ones that don't fit a given regex. I'd also want to ensure that there's only one element in the resulting list, and output that element, but that's a different concern.
|
how to select regex matches in jinja2? toy example Essentially, I want to do something like: ['hello', 'apple', 'rare', 'trim', 'three'] | select(match('.*a[rp].*')) Which would yield: ['apple', 'rare'] what am I talking about? The match filter and select filter. My issue arises from the fact that the select filter only supports unary "tests". I'm on Ansible 1.9.x. my actual use case ...is closer to: lookup('dig', ip_address, qtype="PTR", wantList=True) | select(match("mx\\..*\\.example\\.com")) So, I want to get all the PTR records associated with an IP and then filter out all the ones that don't fit a given regex. I'd also want to ensure that there's only one element in the resulting list, and output that element, but that's a different concern.
|
ansible, jinja2, template-engine
| 16
| 67,408
| 4
|
https://stackoverflow.com/questions/38795908/how-to-select-regex-matches-in-jinja2
|
33,379,378
|
Idempotence and Random Variables in Ansible
|
Is there a way to guarantee idempotence for playbooks that use randomly generated variables? For example, I want to setup my crontabs to trigger emails on multiple servers at different times, so I create random integers using ansible's set_fact module: tasks: - set_fact: first_run_30="{{ 30 | random }}" run_once: yes Then apply those generated variables to my crontab using ansible like so: - name: Setup cron30job cron: name=cron30job minute={{first_run_30}},{{first_run_30 | int + 30}} job='/bin/bash /cron30job.sh' state=present user=root environment: MAILTO: 'me@somelist.com' MAILFROM: 'me@somehost.com' This works very well, however, ansible's indempotence principle is, I believe, broken using this strategy because each time a play is made you see a change: TASK: [Setup cron30job] ***************************************** changed: [127.0.0.1] Further, in the crontab checking under root each time during three separate runs: [ansible]# cat /var/spool/cron/root #Ansible: cron30job 5,35 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 9,39 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 6,36 * * * * /bin/bash /sw/test/cron30job.sh If there is a workaround, or maybe indempotence just will not be possible in my scenario, I would like to know.
|
Idempotence and Random Variables in Ansible Is there a way to guarantee idempotence for playbooks that use randomly generated variables? For example, I want to setup my crontabs to trigger emails on multiple servers at different times, so I create random integers using ansible's set_fact module: tasks: - set_fact: first_run_30="{{ 30 | random }}" run_once: yes Then apply those generated variables to my crontab using ansible like so: - name: Setup cron30job cron: name=cron30job minute={{first_run_30}},{{first_run_30 | int + 30}} job='/bin/bash /cron30job.sh' state=present user=root environment: MAILTO: 'me@somelist.com' MAILFROM: 'me@somehost.com' This works very well, however, ansible's indempotence principle is, I believe, broken using this strategy because each time a play is made you see a change: TASK: [Setup cron30job] ***************************************** changed: [127.0.0.1] Further, in the crontab checking under root each time during three separate runs: [ansible]# cat /var/spool/cron/root #Ansible: cron30job 5,35 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 9,39 * * * * /bin/bash /sw/test/cron30job.sh #Ansible: cron30job 6,36 * * * * /bin/bash /sw/test/cron30job.sh If there is a workaround, or maybe indempotence just will not be possible in my scenario, I would like to know.
|
cron, ansible
| 16
| 8,190
| 3
|
https://stackoverflow.com/questions/33379378/idempotence-and-random-variables-in-ansible
|
26,527,458
|
Ansible multiple hosts with port forwarding
|
I have hosts inventory with multiple hosts each with port forwarding, Hosts file is : [all] 10.80.238.11:20003 10.80.238.11:20001 10.80.238.11:20007 10.80.238.11:20009 I am trying to ping them with a playbook, but always get response from first entry in this case 10.80.238.11:20003 not from others. Authentication is on place, whatever host I move to first place I get response from it but not others, my playbook is: --- - hosts: all remote_user: root gather_facts: no tasks: - name: test connection ping: Any idea how to fix this???
|
Ansible multiple hosts with port forwarding I have hosts inventory with multiple hosts each with port forwarding, Hosts file is : [all] 10.80.238.11:20003 10.80.238.11:20001 10.80.238.11:20007 10.80.238.11:20009 I am trying to ping them with a playbook, but always get response from first entry in this case 10.80.238.11:20003 not from others. Authentication is on place, whatever host I move to first place I get response from it but not others, my playbook is: --- - hosts: all remote_user: root gather_facts: no tasks: - name: test connection ping: Any idea how to fix this???
|
python, network-programming, portforwarding, ansible
| 16
| 12,825
| 1
|
https://stackoverflow.com/questions/26527458/ansible-multiple-hosts-with-port-forwarding
|
57,727,326
|
How do you convert ansible ini inventory into json or yaml
|
Ansible AWX requires inventories to be entered in yaml or json format. When you start learning ansible, you may take the choice to start off with your inventory in ini format. [URL] Is it possible to convert between formats?
|
How do you convert ansible ini inventory into json or yaml Ansible AWX requires inventories to be entered in yaml or json format. When you start learning ansible, you may take the choice to start off with your inventory in ini format. [URL] Is it possible to convert between formats?
|
ansible, ansible-inventory, ansible-awx
| 16
| 23,617
| 2
|
https://stackoverflow.com/questions/57727326/how-do-you-convert-ansible-ini-inventory-into-json-or-yaml
|
32,704,247
|
ansible - variable within variable
|
Ansible 1.9.2 version. Does Ansible supports variable expansion within a variable while evaluating it. I have a task to download 3 zip files from Artifactory. Instead of writing 3 separate tasks within the role, I used ansible's loop in the playbook. In Ansible role's default/main.yml, I have all the required variables defined/available to the role i.e. jmeterplugins_extras_artifactory_url and other (standard / webdriver) are visible to perf_tests role. --- #- Download and install JMeterPlugins # Use get_url when Ansible is 2.0+ is available on the machine (otherwise, we can't use get_url) thus, using wget. - name: Download JMeterPlugins-* command: wget {{ jmeterplugins_{{ item.plugin }}_artifactory_url }} chdir="{{ common_download_dir }}" creates="{{ common_download_dir }}/{{ jmeterplugins_{{ item.plugin }}_file }}" with_items: - { plugin: 'extras' } - { plugin: 'standard' } - { plugin: 'webdriver' } But with the above code, I'm getting an error (as shown below): 15:58:57 TASK: [perf_tests | Download JMeterPlugins-*] ********************************* 15:58:57 <jmeter01.super.fast.jenkins> ESTABLISH CONNECTION FOR USER: cmuser on PORT 22 TO jmeter01.super.fast.jenkins 15:58:57 fatal: [jmeter01.super.fast.jenkins] => Failed to template wget {{ jmeterplugins_{{ item.plugin }}_artifactory_url }} chdir="{{ common_download_dir }}" creates="{{ common_download_dir }}/{{ jmeterplugins_{{ item.plugin }}_file }}": template error while templating string: expected token 'variable_end', got '{' 15:58:57 15:58:57 FATAL: all hosts have already failed -- aborting 15:58:57 15:58:57 PLAY RECAP ******************************************************************** 15:58:57 to retry, use: --limit @/home/cmuser/perf_tests.retry 15:58:57 15:58:57 jmeter01.super.fast.jenkins : ok=23 changed=6 unreachable=1 failed=0 Doesn't ansible supports variable expansion/evaluation if a variable contains another variable (especially when I'm using a loop). I just dont want to expand my simple loop task into 3 different -name tasks for downloading zip files for jmeterplugins_extras, jmeterplugins_standard and jmeterplugins_webdriver separately. It seems like the error is related due to Jinja. How can I use var's value giga in another variable i.e. if var contains giga , then I should get the value of variable "special_giga_variable" ( {{special_{{ var }}_variable}} )? where var was defined in defaults/main.yml as: var: giga
|
ansible - variable within variable Ansible 1.9.2 version. Does Ansible supports variable expansion within a variable while evaluating it. I have a task to download 3 zip files from Artifactory. Instead of writing 3 separate tasks within the role, I used ansible's loop in the playbook. In Ansible role's default/main.yml, I have all the required variables defined/available to the role i.e. jmeterplugins_extras_artifactory_url and other (standard / webdriver) are visible to perf_tests role. --- #- Download and install JMeterPlugins # Use get_url when Ansible is 2.0+ is available on the machine (otherwise, we can't use get_url) thus, using wget. - name: Download JMeterPlugins-* command: wget {{ jmeterplugins_{{ item.plugin }}_artifactory_url }} chdir="{{ common_download_dir }}" creates="{{ common_download_dir }}/{{ jmeterplugins_{{ item.plugin }}_file }}" with_items: - { plugin: 'extras' } - { plugin: 'standard' } - { plugin: 'webdriver' } But with the above code, I'm getting an error (as shown below): 15:58:57 TASK: [perf_tests | Download JMeterPlugins-*] ********************************* 15:58:57 <jmeter01.super.fast.jenkins> ESTABLISH CONNECTION FOR USER: cmuser on PORT 22 TO jmeter01.super.fast.jenkins 15:58:57 fatal: [jmeter01.super.fast.jenkins] => Failed to template wget {{ jmeterplugins_{{ item.plugin }}_artifactory_url }} chdir="{{ common_download_dir }}" creates="{{ common_download_dir }}/{{ jmeterplugins_{{ item.plugin }}_file }}": template error while templating string: expected token 'variable_end', got '{' 15:58:57 15:58:57 FATAL: all hosts have already failed -- aborting 15:58:57 15:58:57 PLAY RECAP ******************************************************************** 15:58:57 to retry, use: --limit @/home/cmuser/perf_tests.retry 15:58:57 15:58:57 jmeter01.super.fast.jenkins : ok=23 changed=6 unreachable=1 failed=0 Doesn't ansible supports variable expansion/evaluation if a variable contains another variable (especially when I'm using a loop). I just dont want to expand my simple loop task into 3 different -name tasks for downloading zip files for jmeterplugins_extras, jmeterplugins_standard and jmeterplugins_webdriver separately. It seems like the error is related due to Jinja. How can I use var's value giga in another variable i.e. if var contains giga , then I should get the value of variable "special_giga_variable" ( {{special_{{ var }}_variable}} )? where var was defined in defaults/main.yml as: var: giga
|
variables, ansible, jinja2
| 16
| 47,069
| 2
|
https://stackoverflow.com/questions/32704247/ansible-variable-within-variable
|
28,023,697
|
ansible creating working cronjobs
|
I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in Ansible and crontabs but so far nothing worked. Whatever i do, i get the Error Message: ERROR: cron is not a legal parameter at this level in an Ansible Playbook I have: Ansible 1.8.1 And for some unknown reasons, my Modules are located in: /usr/lib/python2.6/site-packages/ansible/modules/ I would like to know which precise steps i have to follow to let Ansible install a new cronjob in the crontab file. How precisely must a playbook look like to install a cronjob? What is the command line to start this playbook? I'm asking this odd question because the documentation of cron is insufficient and the examples are not working. Maybe my installation is wrong too, which I want to test out with a working example of cron.
|
ansible creating working cronjobs I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in Ansible and crontabs but so far nothing worked. Whatever i do, i get the Error Message: ERROR: cron is not a legal parameter at this level in an Ansible Playbook I have: Ansible 1.8.1 And for some unknown reasons, my Modules are located in: /usr/lib/python2.6/site-packages/ansible/modules/ I would like to know which precise steps i have to follow to let Ansible install a new cronjob in the crontab file. How precisely must a playbook look like to install a cronjob? What is the command line to start this playbook? I'm asking this odd question because the documentation of cron is insufficient and the examples are not working. Maybe my installation is wrong too, which I want to test out with a working example of cron.
|
cron, ansible
| 16
| 67,345
| 3
|
https://stackoverflow.com/questions/28023697/ansible-creating-working-cronjobs
|
51,373,200
|
Ansible is skipping the debug line
|
I have this task in a role and a debug line beneath it: - name: Restore bootstrap DB command: "mongorestore -v --host localhost:{{ mongodb_net.port }} -d {{ item.dbname }} --dir {{ item.clone_dir }}" register: restore_result with_items: - { dbname: "{{ mongodb_db1_dbname }}", clone_dir: "/var/tmp/db_bootstrap/DB1_CLONE" } - { dbname: "{{ mongodb_db2_dbname }}", clone_dir: "/var/tmp/db_bootstrap/DB2_CLONE" } - debug: var=restore_result verbosity=2 But it's skipping the debug task. TASK [mongodb : Restore bootstrap DB] *************************************************** changed: [xx.xx.xx.167] => (item={u'dbname': u'DB1', u'clone_dir': u'/var/tmp/db_bootstrap/DB1'}) changed: [xx.xx.xx.167] => (item={u'dbname': u'DB2', u'clone_dir': u'/var/tmp/db_bootstrap/DB2'}) TASK [mongodb : debug] ****************************************************************** skipping: [xx.xx.xx.167] When I enable verbose mode, -vv , it shows the content of the registered variable. I'm using Ansible version 2.4.3
|
Ansible is skipping the debug line I have this task in a role and a debug line beneath it: - name: Restore bootstrap DB command: "mongorestore -v --host localhost:{{ mongodb_net.port }} -d {{ item.dbname }} --dir {{ item.clone_dir }}" register: restore_result with_items: - { dbname: "{{ mongodb_db1_dbname }}", clone_dir: "/var/tmp/db_bootstrap/DB1_CLONE" } - { dbname: "{{ mongodb_db2_dbname }}", clone_dir: "/var/tmp/db_bootstrap/DB2_CLONE" } - debug: var=restore_result verbosity=2 But it's skipping the debug task. TASK [mongodb : Restore bootstrap DB] *************************************************** changed: [xx.xx.xx.167] => (item={u'dbname': u'DB1', u'clone_dir': u'/var/tmp/db_bootstrap/DB1'}) changed: [xx.xx.xx.167] => (item={u'dbname': u'DB2', u'clone_dir': u'/var/tmp/db_bootstrap/DB2'}) TASK [mongodb : debug] ****************************************************************** skipping: [xx.xx.xx.167] When I enable verbose mode, -vv , it shows the content of the registered variable. I'm using Ansible version 2.4.3
|
ansible, ansible-2.x
| 16
| 12,948
| 1
|
https://stackoverflow.com/questions/51373200/ansible-is-skipping-the-debug-line
|
44,855,892
|
How to get value of --limit argument inside an Ansible playbook?
|
In ansible, is it possible to get the value of the argument to the "--limit" option within a playbook? I want to do is something like this: --- - hosts: all remote user: root tasks: - name: The value of the --limit argument debug: msg: "argument of --limit is {{ ansible-limit-arg }}" Then when I run he command: $ ansible-playbook getLimitArg.yaml --limit webhosts I'll get this output: argument of --limit is webhost Of course, I made up the name of the variable "ansible-limit-arg", but is there a valid way of doing this? I could specify "webhosts" twice, the second time with --extra-args, but that seems a roundabout way of having to do this.
|
How to get value of --limit argument inside an Ansible playbook? In ansible, is it possible to get the value of the argument to the "--limit" option within a playbook? I want to do is something like this: --- - hosts: all remote user: root tasks: - name: The value of the --limit argument debug: msg: "argument of --limit is {{ ansible-limit-arg }}" Then when I run he command: $ ansible-playbook getLimitArg.yaml --limit webhosts I'll get this output: argument of --limit is webhost Of course, I made up the name of the variable "ansible-limit-arg", but is there a valid way of doing this? I could specify "webhosts" twice, the second time with --extra-args, but that seems a roundabout way of having to do this.
|
ansible
| 16
| 16,069
| 4
|
https://stackoverflow.com/questions/44855892/how-to-get-value-of-limit-argument-inside-an-ansible-playbook
|
66,005,654
|
How to specify "if else" statements in Ansible Jinja2 (.j2) templates?
|
I'm running an if statement in a bash script. And I need to deploy the bash script in a different server. Below is my if else statement. DIR="/backup/db" first_time=true {% if [ -d "$DIR" ]; then %} first_time=false sudo -u tomcat ln -s /backup/app /opt/tomcat/latest/webapps/msales sudo -u tomcat ln -s /backup/store/logs /opt/tomcat/latest/logs .....etc {% fi %} I'm using Ansible to deploy to this script.sh.j2 to the other server. But it says ""msg": "AnsibleError: template error while templating string: expected token ',', got 'string'." How to use if statements in j2 templates?
|
How to specify "if else" statements in Ansible Jinja2 (.j2) templates? I'm running an if statement in a bash script. And I need to deploy the bash script in a different server. Below is my if else statement. DIR="/backup/db" first_time=true {% if [ -d "$DIR" ]; then %} first_time=false sudo -u tomcat ln -s /backup/app /opt/tomcat/latest/webapps/msales sudo -u tomcat ln -s /backup/store/logs /opt/tomcat/latest/logs .....etc {% fi %} I'm using Ansible to deploy to this script.sh.j2 to the other server. But it says ""msg": "AnsibleError: template error while templating string: expected token ',', got 'string'." How to use if statements in j2 templates?
|
bash, ansible, scripting, jinja2
| 16
| 93,403
| 2
|
https://stackoverflow.com/questions/66005654/how-to-specify-if-else-statements-in-ansible-jinja2-j2-templates
|
44,593,915
|
How do I copy a remote file onto my local machine using Ansible?
|
I'm using the command module inside my playbook, and it currently looks like this. - hosts: all tasks: - name: Update tar file command: sudo scp -r username@hostname:/path/from/destination /path/to/destination I've omitted the tasks the take place before this task for the purpose of readability, but what happens when I run this playbook is that it stop at this task. It simply doesn't move forward. I'm sure this is because sudo, so It may want the password for that. I'm not sure how to fix that however.
|
How do I copy a remote file onto my local machine using Ansible? I'm using the command module inside my playbook, and it currently looks like this. - hosts: all tasks: - name: Update tar file command: sudo scp -r username@hostname:/path/from/destination /path/to/destination I've omitted the tasks the take place before this task for the purpose of readability, but what happens when I run this playbook is that it stop at this task. It simply doesn't move forward. I'm sure this is because sudo, so It may want the password for that. I'm not sure how to fix that however.
|
ansible
| 16
| 39,491
| 1
|
https://stackoverflow.com/questions/44593915/how-do-i-copy-a-remote-file-onto-my-local-machine-using-ansible
|
38,188,717
|
How to share handlers?
|
The docs says: Since handlers are tasks too, you can also include handler files from the βhandlers:β section. What I do, playbook.yml : - hosts: all handlers: - include: handlers.yml # - name: h1 # debug: msg=h1 tasks: - debug: msg=test notify: h1 changed_when: true handlers.yml : - name: h1 debug: msg=h1 Then, $ ansible-playbook playbook.yml -i localhost, -k -e ansible_python_interpreter=python2 -v ... TASK [debug] ******************************************************************* ok: [localhost] => { "msg": "test" } PLAY RECAP ********************************************************************* localhost : ok=3 changed=1 unreachable=0 failed=0 ... But when I uncomment the lines, I see $ ansible-playbook playbook.yml -i localhost, -k -e ansible_python_interpreter=python2 -v ... TASK [debug] ******************************************************************* ok: [localhost] => { "msg": "test" } RUNNING HANDLER [h1] *********************************************************** ok: [localhost] => { "msg": "h1" } PLAY RECAP ********************************************************************* localhost : ok=3 changed=1 unreachable=0 failed=0 ... I'm running ansible-2.1.0.0 . What am I doing wrong? That's the first thing I'd like to know. Workarounds come second. UPD Includes can also be used in the βhandlersβ section, for instance, if you want to define how to restart apache, you only have to do that once for all of your playbooks. You might make a handlers.yml that looks like: --- # this might be in a file like handlers/handlers.yml - name: restart apache service: name=apache state=restarted And in your main playbook file, just include it like so, at the bottom of a play: handlers: - include: handlers/handlers.yml
|
How to share handlers? The docs says: Since handlers are tasks too, you can also include handler files from the βhandlers:β section. What I do, playbook.yml : - hosts: all handlers: - include: handlers.yml # - name: h1 # debug: msg=h1 tasks: - debug: msg=test notify: h1 changed_when: true handlers.yml : - name: h1 debug: msg=h1 Then, $ ansible-playbook playbook.yml -i localhost, -k -e ansible_python_interpreter=python2 -v ... TASK [debug] ******************************************************************* ok: [localhost] => { "msg": "test" } PLAY RECAP ********************************************************************* localhost : ok=3 changed=1 unreachable=0 failed=0 ... But when I uncomment the lines, I see $ ansible-playbook playbook.yml -i localhost, -k -e ansible_python_interpreter=python2 -v ... TASK [debug] ******************************************************************* ok: [localhost] => { "msg": "test" } RUNNING HANDLER [h1] *********************************************************** ok: [localhost] => { "msg": "h1" } PLAY RECAP ********************************************************************* localhost : ok=3 changed=1 unreachable=0 failed=0 ... I'm running ansible-2.1.0.0 . What am I doing wrong? That's the first thing I'd like to know. Workarounds come second. UPD Includes can also be used in the βhandlersβ section, for instance, if you want to define how to restart apache, you only have to do that once for all of your playbooks. You might make a handlers.yml that looks like: --- # this might be in a file like handlers/handlers.yml - name: restart apache service: name=apache state=restarted And in your main playbook file, just include it like so, at the bottom of a play: handlers: - include: handlers/handlers.yml
|
ansible
| 16
| 16,522
| 2
|
https://stackoverflow.com/questions/38188717/how-to-share-handlers
|
28,597,029
|
Ansible - How to backup all MySQL databases?
|
I need to take a backup of all existing MySQL databases on my server with Ansible. I'm aware of mysql_db module. It takes the names of the databases I'd like to manipulate on one by one, so I must get the list of existing databases before using that module. Is there any way to backup all MySQL databases at once or to get a list of existing databases with Ansible?
|
Ansible - How to backup all MySQL databases? I need to take a backup of all existing MySQL databases on my server with Ansible. I'm aware of mysql_db module. It takes the names of the databases I'd like to manipulate on one by one, so I must get the list of existing databases before using that module. Is there any way to backup all MySQL databases at once or to get a list of existing databases with Ansible?
|
mysql, ansible
| 16
| 20,537
| 3
|
https://stackoverflow.com/questions/28597029/ansible-how-to-backup-all-mysql-databases
|
24,559,125
|
Why Ansible doesn't read the templates in relative path?
|
I am using Ansible and I have some problems with the templates path. Here is the error output when I execute: $ ansible-playbook -i hosts site.yml PLAY [users] ****************************************************************** GATHERING FACTS *************************************************************** ok: [10.0.3.240] TASK: [templates] ************************************************************* fatal: [10.0.3.240] => {'msg': 'unable to read /home/robe/Desktop/ansible_demo/fig.conf.j2', 'failed': True} fatal: [10.0.3.240] => {'msg': 'unable to read /home/robe/Desktop/ansible_demo/fig.conf.j2', 'failed': True} FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/home/robe/site.retry 10.0.3.240 : ok=1 changed=0 unreachable=1 failed=0 This is my project structure: $ tree . βββ ansible.cfg βββ hosts βββ roles β βββ users β βββ files β βββ handlers β β βββ main.yml β βββ tasks β β βββ main.yml β βββ templates β β βββ fig.conf.j2 β βββ vars β βββ main.yml βββ site.yml βββ Vagrantfile This is my site.yml code: --- - hosts: users remote_user: root sudo: True tasks: - name: templates template: src="fig.conf.j2" dest="/home/vagrant/fig.conf" Then, why Ansible doesn't look into templates directory and it only looks in the root directory.
|
Why Ansible doesn't read the templates in relative path? I am using Ansible and I have some problems with the templates path. Here is the error output when I execute: $ ansible-playbook -i hosts site.yml PLAY [users] ****************************************************************** GATHERING FACTS *************************************************************** ok: [10.0.3.240] TASK: [templates] ************************************************************* fatal: [10.0.3.240] => {'msg': 'unable to read /home/robe/Desktop/ansible_demo/fig.conf.j2', 'failed': True} fatal: [10.0.3.240] => {'msg': 'unable to read /home/robe/Desktop/ansible_demo/fig.conf.j2', 'failed': True} FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/home/robe/site.retry 10.0.3.240 : ok=1 changed=0 unreachable=1 failed=0 This is my project structure: $ tree . βββ ansible.cfg βββ hosts βββ roles β βββ users β βββ files β βββ handlers β β βββ main.yml β βββ tasks β β βββ main.yml β βββ templates β β βββ fig.conf.j2 β βββ vars β βββ main.yml βββ site.yml βββ Vagrantfile This is my site.yml code: --- - hosts: users remote_user: root sudo: True tasks: - name: templates template: src="fig.conf.j2" dest="/home/vagrant/fig.conf" Then, why Ansible doesn't look into templates directory and it only looks in the root directory.
|
ansible
| 16
| 32,649
| 2
|
https://stackoverflow.com/questions/24559125/why-ansible-doesnt-read-the-templates-in-relative-path
|
18,368,427
|
ansible : how to use the variable ${item} from with_items in notify?
|
I am new to Ansible and I am trying to create several virtual environments (one for each project, the list of projects being defined in a variable). The task works well, I got all the folders, however the handler does not work, it does not init each folder with the virtual environment. The ${item} varialbe in the handler does not work. How can I use an handler when I use with_items ? tasks: - name: create virtual env for all projects ${projects} file: state=directory path=${virtualenvs_dir}/${item} with_items: ${projects} notify: deploy virtual env handlers: - name: deploy virtual env command: virtualenv ${virtualenvs_dir}/${item}
|
ansible : how to use the variable ${item} from with_items in notify? I am new to Ansible and I am trying to create several virtual environments (one for each project, the list of projects being defined in a variable). The task works well, I got all the folders, however the handler does not work, it does not init each folder with the virtual environment. The ${item} varialbe in the handler does not work. How can I use an handler when I use with_items ? tasks: - name: create virtual env for all projects ${projects} file: state=directory path=${virtualenvs_dir}/${item} with_items: ${projects} notify: deploy virtual env handlers: - name: deploy virtual env command: virtualenv ${virtualenvs_dir}/${item}
|
ansible
| 16
| 43,341
| 2
|
https://stackoverflow.com/questions/18368427/ansible-how-to-use-the-variable-item-from-with-items-in-notify
|
68,797,541
|
How can we print coloured output of Ansible tasks when Ansible is run through a shell script?
|
I have an Ansible playbook that is called from a bash script as show in the below snippet: #!/bin/bash # Name of script: execute_ansible # Execute ansible playbook ansible-playbook my_ansible_playbook This script is executed as below: bash execute_ansible When executed with the above command, the Ansible playbook my_ansible_playbook is executed correctly. However, the colorised output that would have been displayed had the Ansible playbook been run from the command line directly is not visible. Is there a way we can enable the colorised output to be visible when executed from the shell script?
|
How can we print coloured output of Ansible tasks when Ansible is run through a shell script? I have an Ansible playbook that is called from a bash script as show in the below snippet: #!/bin/bash # Name of script: execute_ansible # Execute ansible playbook ansible-playbook my_ansible_playbook This script is executed as below: bash execute_ansible When executed with the above command, the Ansible playbook my_ansible_playbook is executed correctly. However, the colorised output that would have been displayed had the Ansible playbook been run from the command line directly is not visible. Is there a way we can enable the colorised output to be visible when executed from the shell script?
|
bash, ansible
| 16
| 14,324
| 1
|
https://stackoverflow.com/questions/68797541/how-can-we-print-coloured-output-of-ansible-tasks-when-ansible-is-run-through-a
|
48,881,975
|
Ansible package vs yum module
|
I am a newbie in the Ansible world. I have already created some playbook and I am getting more and more familiar with this technology by the day. In my playbooks I have always used the command yum to install and manage new packages, but recently I found out about another command package that claims to be OS independent. Thus my question: What is the difference between them? In particular, if I create a role and a playbook that I know that will be executed in RHEL environment (where yum is the default package manager), which advantage do I get from using the command package rather than yum ? Thanks in advance for your help.
|
Ansible package vs yum module I am a newbie in the Ansible world. I have already created some playbook and I am getting more and more familiar with this technology by the day. In my playbooks I have always used the command yum to install and manage new packages, but recently I found out about another command package that claims to be OS independent. Thus my question: What is the difference between them? In particular, if I create a role and a playbook that I know that will be executed in RHEL environment (where yum is the default package manager), which advantage do I get from using the command package rather than yum ? Thanks in advance for your help.
|
ansible
| 16
| 15,353
| 2
|
https://stackoverflow.com/questions/48881975/ansible-package-vs-yum-module
|
26,379,508
|
Can we disable pipelining in ansible-playbook but have it in ansible.cfg?
|
I want to keep pipelining in /etc/ansible/ansible.cfg but disable it for one playbook which removes 'requiretty' in /etc/sudoers file
|
Can we disable pipelining in ansible-playbook but have it in ansible.cfg? I want to keep pipelining in /etc/ansible/ansible.cfg but disable it for one playbook which removes 'requiretty' in /etc/sudoers file
|
ansible
| 16
| 6,715
| 3
|
https://stackoverflow.com/questions/26379508/can-we-disable-pipelining-in-ansible-playbook-but-have-it-in-ansible-cfg
|
61,095,210
|
Ansible how to create list of dictionary keys
|
I am probably missing something simple. I have the dictionary in vars.yml deploy_env: dev: schemas: year1: - main - custom year2: - main - custom - security year3: - main - custom Then in my playbook.yml , I have something like - set_fact: years: "{{ deploy_env.dev.schemas }}" - name: Create schemas shell: "mysql ....params go here... {{ item }}" with_nested: - "{{ years }}" The above works fine if schemas in vars.yml were a simple list ie: deploy_env: dev: schemas: - year1 - year2 - year3 But as soon as I add additional items under each year (making this a dictionary(?) I start getting errors on the line: - "{{ years }} I basically want to populate {{ years }} with year1 , year2 , year3 values for this task. I've looked at many examples but everything I looked at was soo complex and it was about how to create dictionaries which is not helpful.
|
Ansible how to create list of dictionary keys I am probably missing something simple. I have the dictionary in vars.yml deploy_env: dev: schemas: year1: - main - custom year2: - main - custom - security year3: - main - custom Then in my playbook.yml , I have something like - set_fact: years: "{{ deploy_env.dev.schemas }}" - name: Create schemas shell: "mysql ....params go here... {{ item }}" with_nested: - "{{ years }}" The above works fine if schemas in vars.yml were a simple list ie: deploy_env: dev: schemas: - year1 - year2 - year3 But as soon as I add additional items under each year (making this a dictionary(?) I start getting errors on the line: - "{{ years }} I basically want to populate {{ years }} with year1 , year2 , year3 values for this task. I've looked at many examples but everything I looked at was soo complex and it was about how to create dictionaries which is not helpful.
|
dictionary, variables, ansible
| 16
| 41,154
| 1
|
https://stackoverflow.com/questions/61095210/ansible-how-to-create-list-of-dictionary-keys
|
29,305,335
|
How can I persist an ansible variable across ansible roles?
|
I've registered a variable in a play. --- - hosts: 127.0.0.1 gather_facts: no connection: local sudo: no vars_files: - vars.yml tasks: - name: build load balancer os_load_balancer: net=mc_net ext_net=vlan3320 name=load_balancer protocol=HTTPS port=80 register: my_lb I can access that variable fine, until I make the request inside a role. For example, in a separate role in the same run, I want to access that registered variable: - debug: var=my_lb I get the following output: {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'my_lb' is undefined", 'failed': True} How can I access variables registered in a separate role, within the same play? Edit for clarity of how things piece together: Top Play -includes: - Sub play 1 - registers variable foo - Sub play 2 -includes: - sub play A - role 1 - role 2 - role 3 - references variable foo in template - Sub play B - Sub play 3
|
How can I persist an ansible variable across ansible roles? I've registered a variable in a play. --- - hosts: 127.0.0.1 gather_facts: no connection: local sudo: no vars_files: - vars.yml tasks: - name: build load balancer os_load_balancer: net=mc_net ext_net=vlan3320 name=load_balancer protocol=HTTPS port=80 register: my_lb I can access that variable fine, until I make the request inside a role. For example, in a separate role in the same run, I want to access that registered variable: - debug: var=my_lb I get the following output: {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'my_lb' is undefined", 'failed': True} How can I access variables registered in a separate role, within the same play? Edit for clarity of how things piece together: Top Play -includes: - Sub play 1 - registers variable foo - Sub play 2 -includes: - sub play A - role 1 - role 2 - role 3 - references variable foo in template - Sub play B - Sub play 3
|
ansible
| 16
| 50,469
| 4
|
https://stackoverflow.com/questions/29305335/how-can-i-persist-an-ansible-variable-across-ansible-roles
|
69,109,062
|
Can't set Ansible fact as integer
|
I am trying to extract the major distro version (which ansible_facts holds as a string) and store it as an integer for later < or > comparison to an integer. When I do this: - set_fact: distromajor: "{{ ansible_facts['distribution_major_version'] | int }}" I find distromajor holds "7" instead of 7 . So later comparisons fail. In fact, the only way I can get it to work is to compare like this: (distromajor|int >=6) and (distromajor|int <= 8) Is this expected behaviour? Why can I not save the distro major version as an int? The closest SO question does not explain why a later integer comparison fails without reconverting the distromajor variable to integer at time of comparison.
|
Can't set Ansible fact as integer I am trying to extract the major distro version (which ansible_facts holds as a string) and store it as an integer for later < or > comparison to an integer. When I do this: - set_fact: distromajor: "{{ ansible_facts['distribution_major_version'] | int }}" I find distromajor holds "7" instead of 7 . So later comparisons fail. In fact, the only way I can get it to work is to compare like this: (distromajor|int >=6) and (distromajor|int <= 8) Is this expected behaviour? Why can I not save the distro major version as an int? The closest SO question does not explain why a later integer comparison fails without reconverting the distromajor variable to integer at time of comparison.
|
ansible, ansible-facts
| 16
| 5,967
| 1
|
https://stackoverflow.com/questions/69109062/cant-set-ansible-fact-as-integer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.