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
|
|---|---|---|---|---|---|---|---|---|
22,390,655
|
Ansible Installation -clang: error: unknown argument: '-mno-fused-madd'
|
So, I've found some other clang error's on here that appear to be somewhat similar, however, the fixes aren't applicable to my situation. I'm using OSX Mavericks and we're trying to get Ansible installed. I got pip to install correctly, but when I try to install Ansible, I get this clang error. We thought, at first, that it might be a version issue, so I re-installed gcc46 after having this same error with gcc49, but I'm still getting the error. Does anyone know how to fix this? My complete error report from the pip.log log file is as follows: cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -Wall -Wstrict-prototypes -Wshorten-64-to-32 -fwrapv -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/MD2.c -o build/temp.macosx-10.9-intel-2.7/src/MD2.o clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future error: command 'cc' failed with exit status 1 ---------------------------------------- Cleaning up... Removing temporary dir /private/tmp/pip_build_root... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/pycrypto/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_7evji-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/pycrypto Exception information: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/req.py", line 1435, in install requirement.install(install_options, global_options, *args, **kwargs) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/req.py", line 706, in install cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/util.py", line 697, in call_subprocess % (command_desc, proc.returncode, cwd)) InstallationError: Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/pycrypto/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_7evji-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/pycrypto Thanks to anyone who can help me with this. We've spent the past several hours trying to get this to install, and it's starting to get fairly frustrating.
|
Ansible Installation -clang: error: unknown argument: '-mno-fused-madd' So, I've found some other clang error's on here that appear to be somewhat similar, however, the fixes aren't applicable to my situation. I'm using OSX Mavericks and we're trying to get Ansible installed. I got pip to install correctly, but when I try to install Ansible, I get this clang error. We thought, at first, that it might be a version issue, so I re-installed gcc46 after having this same error with gcc49, but I'm still getting the error. Does anyone know how to fix this? My complete error report from the pip.log log file is as follows: cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -Wall -Wstrict-prototypes -Wshorten-64-to-32 -fwrapv -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/MD2.c -o build/temp.macosx-10.9-intel-2.7/src/MD2.o clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future error: command 'cc' failed with exit status 1 ---------------------------------------- Cleaning up... Removing temporary dir /private/tmp/pip_build_root... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/pycrypto/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_7evji-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/pycrypto Exception information: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/req.py", line 1435, in install requirement.install(install_options, global_options, *args, **kwargs) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/req.py", line 706, in install cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False) File "/Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg/pip/util.py", line 697, in call_subprocess % (command_desc, proc.returncode, cwd)) InstallationError: Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/pycrypto/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-_7evji-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/pycrypto Thanks to anyone who can help me with this. We've spent the past several hours trying to get this to install, and it's starting to get fairly frustrating.
|
gcc, osx-mavericks, ansible
| 23
| 20,102
| 3
|
https://stackoverflow.com/questions/22390655/ansible-installation-clang-error-unknown-argument-mno-fused-madd
|
30,516,011
|
Ansible random UUID generation
|
In my Ansible script, I want to generate UUIDs on the fly and use them later on. Here is my approach: - shell: echo uuidgen with_sequence: count=5 register: uuid_list - uri: url: [URL] method: POST body: "{{ item.item.stdout }}" with_items: uuid_list.result However I get the following error: fatal: [localhost] => One or more undefined variables: 'str object' has no attribute 'stdout' How can I solve this issue?
|
Ansible random UUID generation In my Ansible script, I want to generate UUIDs on the fly and use them later on. Here is my approach: - shell: echo uuidgen with_sequence: count=5 register: uuid_list - uri: url: [URL] method: POST body: "{{ item.item.stdout }}" with_items: uuid_list.result However I get the following error: fatal: [localhost] => One or more undefined variables: 'str object' has no attribute 'stdout' How can I solve this issue?
|
ansible
| 23
| 48,983
| 7
|
https://stackoverflow.com/questions/30516011/ansible-random-uuid-generation
|
45,840,664
|
Installing NodeJS LTS for Ansible
|
I'm looking for an appropriate Ansible Role or Ansible YAML file for installing NodeJS LTS on a Ubuntu 16.04.3 xenial system. I tried more than 10 Ansible roles from Galaxy but didn't find any of them working (throws error such as potentially dangerous to add this PPA etc. . Can anyone provide any Ansible playbook or suggest me a role to install NodeJS LTS on Ubuntu 16.04?
|
Installing NodeJS LTS for Ansible I'm looking for an appropriate Ansible Role or Ansible YAML file for installing NodeJS LTS on a Ubuntu 16.04.3 xenial system. I tried more than 10 Ansible roles from Galaxy but didn't find any of them working (throws error such as potentially dangerous to add this PPA etc. . Can anyone provide any Ansible playbook or suggest me a role to install NodeJS LTS on Ubuntu 16.04?
|
node.js, ansible, ansible-role
| 23
| 30,577
| 4
|
https://stackoverflow.com/questions/45840664/installing-nodejs-lts-for-ansible
|
48,033,923
|
Ansible: How to print WARNINGs from playbook?
|
Can I print a warning message from Ansible? Like as Ansible does for an internal warning: [WARNING]: Ignoring invalid attribute: xx The targeted use are warning, that are not an error, so they should not end the playbook execution, but they should be clearly visible (in standard Ansible purple color). Example usage: I have some hardcoded URL of the latest release. The playbook downloads the latest avaiable URL. And print warning if the URLs differs. As the source is not trusted, the downloaded URL is should be used only for comparison, but not used directly.
|
Ansible: How to print WARNINGs from playbook? Can I print a warning message from Ansible? Like as Ansible does for an internal warning: [WARNING]: Ignoring invalid attribute: xx The targeted use are warning, that are not an error, so they should not end the playbook execution, but they should be clearly visible (in standard Ansible purple color). Example usage: I have some hardcoded URL of the latest release. The playbook downloads the latest avaiable URL. And print warning if the URLs differs. As the source is not trusted, the downloaded URL is should be used only for comparison, but not used directly.
|
ansible
| 23
| 28,469
| 5
|
https://stackoverflow.com/questions/48033923/ansible-how-to-print-warnings-from-playbook
|
37,652,464
|
How to run Ansible without hosts file
|
How to run Ansible without hosts file? just like: $ ansible --"Some Options" IP -a 'uptime'
|
How to run Ansible without hosts file How to run Ansible without hosts file? just like: $ ansible --"Some Options" IP -a 'uptime'
|
shell, ansible
| 23
| 32,998
| 4
|
https://stackoverflow.com/questions/37652464/how-to-run-ansible-without-hosts-file
|
42,660,653
|
How can I use a condition to set a variable value in Ansible?
|
I have two variables: a , b . I want to assign a value to a variable c based on which: a or b contains greater numerical value. This what I tried: - set_fact: c: "test1" when: a <= b - set_fact: c: "test2" when: b <= a Look like it always sets c to test1 not test2 .
|
How can I use a condition to set a variable value in Ansible? I have two variables: a , b . I want to assign a value to a variable c based on which: a or b contains greater numerical value. This what I tried: - set_fact: c: "test1" when: a <= b - set_fact: c: "test2" when: b <= a Look like it always sets c to test1 not test2 .
|
ansible
| 23
| 39,043
| 1
|
https://stackoverflow.com/questions/42660653/how-can-i-use-a-condition-to-set-a-variable-value-in-ansible
|
28,610,904
|
Using variables for file name and file contents in lineinfile module
|
I am trying to read the contents of a file, store these in a variable and then insert them into another file if they don't already exist. So, how I'm attempting to go about this is as follows: # Create a variable that represents the path to the file that you want to read from ssh_public_key_file: '../../jenkins_master/files/{{ hostvars[inventory_hostname]["environment"] }}/id_rsa.pub' # Create a variable that represents the contents of this file: ssh_public_key: "{{ lookup('file', '{{ ssh_public_key_file }}') }}" I then use these variables in my Ansible playbook as follows: - name: Install SSH authorized key lineinfile: create=yes dest=~/.ssh/authorized_keys line=" {{ ssh_public_key }}" mode=0644 However, when I try and run the playbook, I get the following error message: could not locate file in lookup: {{ ssh_public_key_file }} Can anyone recommend a solution or suggest what I may have done wrong? Thanks, SeΓ‘n
|
Using variables for file name and file contents in lineinfile module I am trying to read the contents of a file, store these in a variable and then insert them into another file if they don't already exist. So, how I'm attempting to go about this is as follows: # Create a variable that represents the path to the file that you want to read from ssh_public_key_file: '../../jenkins_master/files/{{ hostvars[inventory_hostname]["environment"] }}/id_rsa.pub' # Create a variable that represents the contents of this file: ssh_public_key: "{{ lookup('file', '{{ ssh_public_key_file }}') }}" I then use these variables in my Ansible playbook as follows: - name: Install SSH authorized key lineinfile: create=yes dest=~/.ssh/authorized_keys line=" {{ ssh_public_key }}" mode=0644 However, when I try and run the playbook, I get the following error message: could not locate file in lookup: {{ ssh_public_key_file }} Can anyone recommend a solution or suggest what I may have done wrong? Thanks, SeΓ‘n
|
ansible
| 23
| 36,262
| 2
|
https://stackoverflow.com/questions/28610904/using-variables-for-file-name-and-file-contents-in-lineinfile-module
|
21,063,159
|
How to skip role executing in Ansible
|
I try to write the playbook.yml for my vagrant machine and I'm faced with the following problem. Ansible prompt me to set these variables and I set these variables to null/false/no/[just enter], but the roles is executed no matter! How can I prevent this behavior? I just want no actions if no vars are set.. --- - name: Deploy Webserver hosts: webservers vars_prompt: run_common: "Run common tasks?" run_wordpress: "Run Wordpress tasks?" run_yii: "Run Yii tasks?" run_mariadb: "Run MariaDB tasks?" run_nginx: "Run Nginx tasks?" run_php5: "Run PHP5 tasks?" roles: - { role: common, when: run_common is defined } - { role: mariadb, when: run_mariadb is defined } - { role: wordpress, when: run_wordpress is defined } - { role: yii, when: run_yii is defined } - { role: nginx, when: run_nginx is defined } - { role: php5, when: run_php5 is defined }
|
How to skip role executing in Ansible I try to write the playbook.yml for my vagrant machine and I'm faced with the following problem. Ansible prompt me to set these variables and I set these variables to null/false/no/[just enter], but the roles is executed no matter! How can I prevent this behavior? I just want no actions if no vars are set.. --- - name: Deploy Webserver hosts: webservers vars_prompt: run_common: "Run common tasks?" run_wordpress: "Run Wordpress tasks?" run_yii: "Run Yii tasks?" run_mariadb: "Run MariaDB tasks?" run_nginx: "Run Nginx tasks?" run_php5: "Run PHP5 tasks?" roles: - { role: common, when: run_common is defined } - { role: mariadb, when: run_mariadb is defined } - { role: wordpress, when: run_wordpress is defined } - { role: yii, when: run_yii is defined } - { role: nginx, when: run_nginx is defined } - { role: php5, when: run_php5 is defined }
|
deployment, webserver, vagrant, administration, ansible
| 23
| 37,028
| 1
|
https://stackoverflow.com/questions/21063159/how-to-skip-role-executing-in-ansible
|
48,367,708
|
Ansible get hostname as defined in inventory
|
In my inventory I define hosts like this: [server1] 141.151.176.223 I am looking for a variable which keeps the server1 name, as I am using it to define server hostname. inventory_hostname is set to 141.151.176.223 ansible_hostname as well as inventory_hostname_short is set to 148 . To workaround this problem I am setting my own variable like this: [server1] 141.151.176.223 hostname=server1 but I am not satisfied with this approach. Any ideas?
|
Ansible get hostname as defined in inventory In my inventory I define hosts like this: [server1] 141.151.176.223 I am looking for a variable which keeps the server1 name, as I am using it to define server hostname. inventory_hostname is set to 141.151.176.223 ansible_hostname as well as inventory_hostname_short is set to 148 . To workaround this problem I am setting my own variable like this: [server1] 141.151.176.223 hostname=server1 but I am not satisfied with this approach. Any ideas?
|
ansible, hostname, ansible-inventory
| 23
| 49,641
| 2
|
https://stackoverflow.com/questions/48367708/ansible-get-hostname-as-defined-in-inventory
|
29,806,673
|
Daemonizing an executable in ansible
|
I am trying to create a task in ansible which executes a shell command to run an executable in daemon mode using &. Something like following -name: Start daemon shell: myexeprogram arg1 arg2 & What am seeing is if I keep & the task returns immediately and the process is not started . If I remove & ansible task waits for quite some time without returning. Appreciate suggestion on proper way to start program in daemon mode through ansible. Pls note that I dont want to run this as a service but an adhoc background process based on certain conditions.
|
Daemonizing an executable in ansible I am trying to create a task in ansible which executes a shell command to run an executable in daemon mode using &. Something like following -name: Start daemon shell: myexeprogram arg1 arg2 & What am seeing is if I keep & the task returns immediately and the process is not started . If I remove & ansible task waits for quite some time without returning. Appreciate suggestion on proper way to start program in daemon mode through ansible. Pls note that I dont want to run this as a service but an adhoc background process based on certain conditions.
|
shell, daemon, ansible
| 23
| 22,992
| 5
|
https://stackoverflow.com/questions/29806673/daemonizing-an-executable-in-ansible
|
21,638,996
|
Ansible multiple inventory file
|
I am trying to use multiple inventory file and dynamic inventory with Ansible 1.4 and dev. Ansible returns No hosts matched . I have a simulated scenario with two hosts file in a directory test the content of the directory is listed. hosts1.ini [group1] test1 ansible_ssh_host=127.0.0.1 test2 ansible_ssh_host=127.0.0.2 [group2] test3 ansible_ssh_host=127.0.0.3 hosts2.ini [group3] test4 ansible_ssh_host=127.0.0.4 [group4] test5 ansible_ssh_host=127.0.0.4 test6 ansible_ssh_host=127.0.0.5 if I run ansible -i test --list-hosts all it returns No hosts matched . I digged into the code and found dir.py with a small amended i got it too work. But I think i must have done something wrong and the hack is not required. Any ideas on how to solve it ?
|
Ansible multiple inventory file I am trying to use multiple inventory file and dynamic inventory with Ansible 1.4 and dev. Ansible returns No hosts matched . I have a simulated scenario with two hosts file in a directory test the content of the directory is listed. hosts1.ini [group1] test1 ansible_ssh_host=127.0.0.1 test2 ansible_ssh_host=127.0.0.2 [group2] test3 ansible_ssh_host=127.0.0.3 hosts2.ini [group3] test4 ansible_ssh_host=127.0.0.4 [group4] test5 ansible_ssh_host=127.0.0.4 test6 ansible_ssh_host=127.0.0.5 if I run ansible -i test --list-hosts all it returns No hosts matched . I digged into the code and found dir.py with a small amended i got it too work. But I think i must have done something wrong and the hack is not required. Any ideas on how to solve it ?
|
ansible
| 23
| 19,981
| 3
|
https://stackoverflow.com/questions/21638996/ansible-multiple-inventory-file
|
61,295,544
|
Ansible local_action on host without local ssh daemon
|
How can I run a local command on a Ansible control server, if that control server does not have a SSH daemon running? If I run the following playbook: - name: Test commands hosts: localhost connection: local gather_facts: false tasks: - name: Test local action local_action: command echo "hello world" I get the following error: fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host localhost port 22: Connection refused", "unreachable": true} It seems that local_action is the same as delegate_to: 127.0.0.1 , so Ansible tries to ssh to the localhost. However, there is no SSH daemon running on the local controller host (only on the remote machines). So my immediate question is how to run a specific command from Ansible, without Ansible first trying to SSH to localhost. Crucial addition, not in the original question: My host_vars contained the following line: ansible_connection: ssh
|
Ansible local_action on host without local ssh daemon How can I run a local command on a Ansible control server, if that control server does not have a SSH daemon running? If I run the following playbook: - name: Test commands hosts: localhost connection: local gather_facts: false tasks: - name: Test local action local_action: command echo "hello world" I get the following error: fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host localhost port 22: Connection refused", "unreachable": true} It seems that local_action is the same as delegate_to: 127.0.0.1 , so Ansible tries to ssh to the localhost. However, there is no SSH daemon running on the local controller host (only on the remote machines). So my immediate question is how to run a specific command from Ansible, without Ansible first trying to SSH to localhost. Crucial addition, not in the original question: My host_vars contained the following line: ansible_connection: ssh
|
ansible
| 23
| 30,391
| 3
|
https://stackoverflow.com/questions/61295544/ansible-local-action-on-host-without-local-ssh-daemon
|
44,719,303
|
unable to create a directory path using ansible unarchive module?
|
I am trying to download and extract a tar archive in the remote machine and remote destination must be created if not exists. BUT it is not happening. ERROR: destination directory doesn't exist MYCODE: - unarchive: src: [URL] dest: /opt/tomcat/ creates: yes remote_src: True NOTE: * running the play as root. thanks in advance
|
unable to create a directory path using ansible unarchive module? I am trying to download and extract a tar archive in the remote machine and remote destination must be created if not exists. BUT it is not happening. ERROR: destination directory doesn't exist MYCODE: - unarchive: src: [URL] dest: /opt/tomcat/ creates: yes remote_src: True NOTE: * running the play as root. thanks in advance
|
ansible
| 23
| 35,196
| 1
|
https://stackoverflow.com/questions/44719303/unable-to-create-a-directory-path-using-ansible-unarchive-module
|
35,328,177
|
How to import a .py file into an Ansible Module?
|
My Ansible directory structure looks something like this. Ansible-Repo | +-- playbooks | | | +-- run_custom_module1 | +-- library | | | +-- custom_module1 | +-- custom_module2 | +-- bin | | | +-- usefulpythonfunctions.py I want to be able to import usefulpythonfunctions.py from the bin inside my Ansible Module. I have an import usefulpythonfunctions.py at the top of my module, but I receive the following error when I run the playbook. \r\nImportError: No module named usefulpythonfunctions\r\n", "msg": "MODULE FAILURE", "parsed": false}
|
How to import a .py file into an Ansible Module? My Ansible directory structure looks something like this. Ansible-Repo | +-- playbooks | | | +-- run_custom_module1 | +-- library | | | +-- custom_module1 | +-- custom_module2 | +-- bin | | | +-- usefulpythonfunctions.py I want to be able to import usefulpythonfunctions.py from the bin inside my Ansible Module. I have an import usefulpythonfunctions.py at the top of my module, but I receive the following error when I run the playbook. \r\nImportError: No module named usefulpythonfunctions\r\n", "msg": "MODULE FAILURE", "parsed": false}
|
python, ansible
| 23
| 14,566
| 4
|
https://stackoverflow.com/questions/35328177/how-to-import-a-py-file-into-an-ansible-module
|
21,389,364
|
Ansible handler does not run multiple handler tasks
|
We have one Ansible role that needs to run three tasks in the handlers/main.yml task file, but it only runs the first task. How do I force it to run the other two tasks? I do have the ignore flag on for if the first task fails. The tasks/main.yml file looks like: - name: openfire | Copy plugins into openfire/plugins copy: src={{ srcdir }}/xmpp/{{ item }} dest=${bindir}/openfire/plugins/{{ item }} with_items: - x.jar - y.jar sudo: yes sudo_user: ${tomcat_user} notify: restart openfire - name: openfire | Copy jars into openfire/lib copy: src={{ srcdir }}/xmpp/{{ item }} dest=${bindir}/openfire/lib/{{ item }} with_items: - a.jar - b.jar sudo: yes sudo_user: ${tomcat_user} notify: restart openfire The handlers/main.yml file looks like: - name: restart openfire service: name=openfire state=stopped ignore_errors: true sudo: yes - name: restart openfire file: path=/var/run/openfire.pid state=absent sudo: yes - name: restart openfire service: name=openfire state=restarted enabled=yes sudo: yes Only the first handler task (shut down openfire) runs.
|
Ansible handler does not run multiple handler tasks We have one Ansible role that needs to run three tasks in the handlers/main.yml task file, but it only runs the first task. How do I force it to run the other two tasks? I do have the ignore flag on for if the first task fails. The tasks/main.yml file looks like: - name: openfire | Copy plugins into openfire/plugins copy: src={{ srcdir }}/xmpp/{{ item }} dest=${bindir}/openfire/plugins/{{ item }} with_items: - x.jar - y.jar sudo: yes sudo_user: ${tomcat_user} notify: restart openfire - name: openfire | Copy jars into openfire/lib copy: src={{ srcdir }}/xmpp/{{ item }} dest=${bindir}/openfire/lib/{{ item }} with_items: - a.jar - b.jar sudo: yes sudo_user: ${tomcat_user} notify: restart openfire The handlers/main.yml file looks like: - name: restart openfire service: name=openfire state=stopped ignore_errors: true sudo: yes - name: restart openfire file: path=/var/run/openfire.pid state=absent sudo: yes - name: restart openfire service: name=openfire state=restarted enabled=yes sudo: yes Only the first handler task (shut down openfire) runs.
|
handler, ansible
| 22
| 36,867
| 4
|
https://stackoverflow.com/questions/21389364/ansible-handler-does-not-run-multiple-handler-tasks
|
38,131,804
|
Getting "ImportError: No Module named yaml" error
|
Computer: MacBook Pro mid 2012, running El Capitan 10.11.4 Python version 2.7.10 I've been trying to install ansible from source, and I've run these two commands (following the steps on ansibles documentation): git clone git://github.com/ansible/ansible.git --recursive cd ./ansible and then ran this source ./hacking/env-setup I've also already installed these packages sudo pip install paramiko PyYAML Jinja2 httplib2 six However, if I try and run ansible by typing it in the terminal, I get the following error. Traceback (most recent call last): File "/Users/[myusr]/rock/ansible/bin/ansible", line 81, in <module> from ansible.cli.adhoc import AdHocCLI as mycli File "/Users/[myusr]/rock/ansible/lib/ansible/cli/__init__.py", line 27, in <module> import yaml ImportError: No module named yaml What should be done here?
|
Getting "ImportError: No Module named yaml" error Computer: MacBook Pro mid 2012, running El Capitan 10.11.4 Python version 2.7.10 I've been trying to install ansible from source, and I've run these two commands (following the steps on ansibles documentation): git clone git://github.com/ansible/ansible.git --recursive cd ./ansible and then ran this source ./hacking/env-setup I've also already installed these packages sudo pip install paramiko PyYAML Jinja2 httplib2 six However, if I try and run ansible by typing it in the terminal, I get the following error. Traceback (most recent call last): File "/Users/[myusr]/rock/ansible/bin/ansible", line 81, in <module> from ansible.cli.adhoc import AdHocCLI as mycli File "/Users/[myusr]/rock/ansible/lib/ansible/cli/__init__.py", line 27, in <module> import yaml ImportError: No module named yaml What should be done here?
|
macos, yaml, ansible
| 22
| 70,729
| 7
|
https://stackoverflow.com/questions/38131804/getting-importerror-no-module-named-yaml-error
|
19,857,343
|
Display the time it takes each vagrant ansible task to complete
|
I'm converting a vagrant provisioner from shell to ansible and I was wondering if there's any option to show the actual time it takes to complete each task? Ideally I want to benchmark the difference between installing multiple packages in yum using a shell: method and the in built yum: with_items method. ATM I'm sitting here with a stop watch but I need accurate times for this.
|
Display the time it takes each vagrant ansible task to complete I'm converting a vagrant provisioner from shell to ansible and I was wondering if there's any option to show the actual time it takes to complete each task? Ideally I want to benchmark the difference between installing multiple packages in yum using a shell: method and the in built yum: with_items method. ATM I'm sitting here with a stop watch but I need accurate times for this.
|
task, benchmarking, vagrant, provisioning, ansible
| 22
| 16,714
| 5
|
https://stackoverflow.com/questions/19857343/display-the-time-it-takes-each-vagrant-ansible-task-to-complete
|
15,231,661
|
How do I create a user and set a password using ansible?
|
The documentation refers us to the github example , but this is a bit sparse and mysterious. It says this: # created with: # crypt.crypt('This is my Password', '$1$SomeSalt') password: $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI. but crypt.crypt doesn't emit what the example shows. It also uses MD5. I tried this: # python import crypt crypt.crypt('This is my Password', '$6$somereallyniceandbigrandomsalt$') >> '$69LxCegsnIwI' but the password field of user should get something like this: password: $6$somereallyniceandbigrandomsalt$UqddPX3r4kH3UL5jq5/ZI. which includes three $ delimiters separating the 6 (which signifies that its a SHA-512 hash), the salt, and the crypted password. Note that the python crypt docs don't mention anything about the $N format. Questions: Is the salt, as supplied to crypt.crypt , supposed to end with a trailing $ or is it in $N$SALT format? Python docs refer to DES, but how is SHA-512 or MD5 being called and where is the documention for this? Am I really supposed to take the output of crypt.crypt and cut off the first $6 and make $N$SALT$CRYPTED ? Is this what ansible needs?
|
How do I create a user and set a password using ansible? The documentation refers us to the github example , but this is a bit sparse and mysterious. It says this: # created with: # crypt.crypt('This is my Password', '$1$SomeSalt') password: $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI. but crypt.crypt doesn't emit what the example shows. It also uses MD5. I tried this: # python import crypt crypt.crypt('This is my Password', '$6$somereallyniceandbigrandomsalt$') >> '$69LxCegsnIwI' but the password field of user should get something like this: password: $6$somereallyniceandbigrandomsalt$UqddPX3r4kH3UL5jq5/ZI. which includes three $ delimiters separating the 6 (which signifies that its a SHA-512 hash), the salt, and the crypted password. Note that the python crypt docs don't mention anything about the $N format. Questions: Is the salt, as supplied to crypt.crypt , supposed to end with a trailing $ or is it in $N$SALT format? Python docs refer to DES, but how is SHA-512 or MD5 being called and where is the documention for this? Am I really supposed to take the output of crypt.crypt and cut off the first $6 and make $N$SALT$CRYPTED ? Is this what ansible needs?
|
cryptography, pycrypto, ansible
| 22
| 36,486
| 8
|
https://stackoverflow.com/questions/15231661/how-do-i-create-a-user-and-set-a-password-using-ansible
|
46,929,624
|
Failed to connect to the host via ssh: Host key verification failed.\r\n
|
Getting error when i try to connect to hosts in ansible I am able to ping ssh_connection in local host (ansible), but not in jenkins pipeline build. I have tried almost everything. ---------- [FPipeline] Running shell script + ansible all -m ping -vvv ansible 2.4.0.0 config file = /var/lib/jenkins/workspace/FPipeline/ansible.cfg configured module search path = [u'/var/lib/jenkins/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /bin/ansible python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] Using /var/lib/jenkins/workspace/FPipeline/ansible.cfg as config file Parsed /etc/ansible/hosts inventory source with ini plugin META: ran handlers Using module file /usr/lib/python2.7/site- packages/ansible/modules/system/ping.py <localhost> ESTABLISH SSH CONNECTION FOR USER: None <localhost> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with- mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/var/lib/jenkins/.ansible/cp/8a5a4c6a60 localhost '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' Using module file /usr/lib/python2.7/site- packages/ansible/modules/system/ping.py <192.168.219.131> ESTABLISH SSH CONNECTION FOR USER: None <192.168.219.131> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/var/lib/jenkins/.ansible/cp/81147ff3f7 192.168.219.131 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' <192.168.219.131> (255, '', 'Host key verification failed.\r\n') server1 | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Host key verification failed.\r\n", "unreachable": true } <localhost> (255, '', 'Host key verification failed.\r\n') localhost | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Host key verification failed.\r\n", "unreachable": true } ---------- Can you please help me regarding this...
|
Failed to connect to the host via ssh: Host key verification failed.\r\n Getting error when i try to connect to hosts in ansible I am able to ping ssh_connection in local host (ansible), but not in jenkins pipeline build. I have tried almost everything. ---------- [FPipeline] Running shell script + ansible all -m ping -vvv ansible 2.4.0.0 config file = /var/lib/jenkins/workspace/FPipeline/ansible.cfg configured module search path = [u'/var/lib/jenkins/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /bin/ansible python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] Using /var/lib/jenkins/workspace/FPipeline/ansible.cfg as config file Parsed /etc/ansible/hosts inventory source with ini plugin META: ran handlers Using module file /usr/lib/python2.7/site- packages/ansible/modules/system/ping.py <localhost> ESTABLISH SSH CONNECTION FOR USER: None <localhost> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with- mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/var/lib/jenkins/.ansible/cp/8a5a4c6a60 localhost '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' Using module file /usr/lib/python2.7/site- packages/ansible/modules/system/ping.py <192.168.219.131> ESTABLISH SSH CONNECTION FOR USER: None <192.168.219.131> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/var/lib/jenkins/.ansible/cp/81147ff3f7 192.168.219.131 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"'' <192.168.219.131> (255, '', 'Host key verification failed.\r\n') server1 | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Host key verification failed.\r\n", "unreachable": true } <localhost> (255, '', 'Host key verification failed.\r\n') localhost | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Host key verification failed.\r\n", "unreachable": true } ---------- Can you please help me regarding this...
|
linux, jenkins, ssh, ansible
| 22
| 56,008
| 7
|
https://stackoverflow.com/questions/46929624/failed-to-connect-to-the-host-via-ssh-host-key-verification-failed-r-n
|
39,069,311
|
Terraform: How to run remote-exec more than once?
|
I have noticed that terraform will only run "file", "remote-exec" or "local-exec" on resources once. Once a resource is provisioned if the commands in a "remote-exec" are changed or a file from the provisioner "file" is changed then terraform will not make any changes to the instance. So how to I get terraform to run provisioner "file", "remote-exec" or "local-exec" everytime I run a terraform apply? For more details: Often I have had a resource provisioned partially due to an error from "remote-exec" causes terraform to stop (mostly due to me entering in the wrong commands while I'm writing my script). Running terraform again after this will cause the resource previously created to be destroyed and force terraform to create a new resource from scratch. This is also the only way I can run "remote-exec" twice on a resource... by creating it over from scratch. This is really a drawback to terraform as opposed to ansible, which can do the same exact job as terraform except that it is totally idempotent. When using Ansible with tasks such as "ec2", "shell" and "copy" I can achieve the same tasks as terraform only each of those tasks will be idempotent. Ansible will automatically recognise when it doesn't need to make changes, where it does and because of this it can pick up where a failed ansible-playbook left off without destroying everything and starting from scratch. Terraform lacks this feature. For reference here is a simple terraform resource block for an ec2 instance that uses both "remote-exec" and "file" provisioners: resource "aws_instance" "test" { count = ${var.amt} ami = "ami-2d39803a" instance_type = "t2.micro" key_name = "ansible_aws" tags { name = "test${count.index}" } #creates ssh connection to consul servers connection { user = "ubuntu" private_key="${file("/home/ubuntu/.ssh/id_rsa")}" agent = true timeout = "3m" } provisioner "remote-exec" { inline = [<<EOF sudo apt-get update sudo apt-get install curl unzip echo hi EOF ] } #copying a file over provisioner "file" { source = "scripts/test.txt" destination = "/path/to/file/test.txt" } }
|
Terraform: How to run remote-exec more than once? I have noticed that terraform will only run "file", "remote-exec" or "local-exec" on resources once. Once a resource is provisioned if the commands in a "remote-exec" are changed or a file from the provisioner "file" is changed then terraform will not make any changes to the instance. So how to I get terraform to run provisioner "file", "remote-exec" or "local-exec" everytime I run a terraform apply? For more details: Often I have had a resource provisioned partially due to an error from "remote-exec" causes terraform to stop (mostly due to me entering in the wrong commands while I'm writing my script). Running terraform again after this will cause the resource previously created to be destroyed and force terraform to create a new resource from scratch. This is also the only way I can run "remote-exec" twice on a resource... by creating it over from scratch. This is really a drawback to terraform as opposed to ansible, which can do the same exact job as terraform except that it is totally idempotent. When using Ansible with tasks such as "ec2", "shell" and "copy" I can achieve the same tasks as terraform only each of those tasks will be idempotent. Ansible will automatically recognise when it doesn't need to make changes, where it does and because of this it can pick up where a failed ansible-playbook left off without destroying everything and starting from scratch. Terraform lacks this feature. For reference here is a simple terraform resource block for an ec2 instance that uses both "remote-exec" and "file" provisioners: resource "aws_instance" "test" { count = ${var.amt} ami = "ami-2d39803a" instance_type = "t2.micro" key_name = "ansible_aws" tags { name = "test${count.index}" } #creates ssh connection to consul servers connection { user = "ubuntu" private_key="${file("/home/ubuntu/.ssh/id_rsa")}" agent = true timeout = "3m" } provisioner "remote-exec" { inline = [<<EOF sudo apt-get update sudo apt-get install curl unzip echo hi EOF ] } #copying a file over provisioner "file" { source = "scripts/test.txt" destination = "/path/to/file/test.txt" } }
|
ansible, terraform, idempotent
| 22
| 22,591
| 4
|
https://stackoverflow.com/questions/39069311/terraform-how-to-run-remote-exec-more-than-once
|
33,400,771
|
Check if key exists in a dict in Jinja2 template on ansible
|
I have a host_var in ansible with dict with all interfaces: --- interfaces: vlan0: ip: 127.0.0.1 mask: 255.255.255.0 state: true vlan2: ip: 127.0.1.1 mask: 255.255.255.0 state: true And I want to check if dict has a key vlan1 if ok put to template value vlan1.ip else put vlan2.ip . {% if interfaces.vlan1 %} # and also I try {% if 'vlan1' in interfaces %} {{ interfaces.vlan1.ip }}; {% else %} {{ interfaces.vlan2.ip|default("127.0.0.1") }}; {% endif %}; But i have an error: fatal: [127.0.0.1] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'vlan1'", 'failed': True} I found that it have to be work in Jinja2 but it seems to doesn't work in ansible. Maybe someone have another way for solving this problem? When I define vlan1 it works fine. Ansible version 1.9.2 I was trying to reproduce it in python and have no error if my dictionary have not key vlan1 . thanks to @GUIDO >>> from jinja2 import Template >>> b = Template(""" ... {% if interfaces.vlan1 %} ... {{ interfaces.vlan1.ip }} ... {% else %} ... {{ interfaces.vlan2.ip|default("127.0.3.1") }} ... {% endif %}""") >>> b.render(interfaces={'vlan3':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.2.1\n' >>> b.render(interfaces={'vlan1':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.1.1\n'
|
Check if key exists in a dict in Jinja2 template on ansible I have a host_var in ansible with dict with all interfaces: --- interfaces: vlan0: ip: 127.0.0.1 mask: 255.255.255.0 state: true vlan2: ip: 127.0.1.1 mask: 255.255.255.0 state: true And I want to check if dict has a key vlan1 if ok put to template value vlan1.ip else put vlan2.ip . {% if interfaces.vlan1 %} # and also I try {% if 'vlan1' in interfaces %} {{ interfaces.vlan1.ip }}; {% else %} {{ interfaces.vlan2.ip|default("127.0.0.1") }}; {% endif %}; But i have an error: fatal: [127.0.0.1] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'vlan1'", 'failed': True} I found that it have to be work in Jinja2 but it seems to doesn't work in ansible. Maybe someone have another way for solving this problem? When I define vlan1 it works fine. Ansible version 1.9.2 I was trying to reproduce it in python and have no error if my dictionary have not key vlan1 . thanks to @GUIDO >>> from jinja2 import Template >>> b = Template(""" ... {% if interfaces.vlan1 %} ... {{ interfaces.vlan1.ip }} ... {% else %} ... {{ interfaces.vlan2.ip|default("127.0.3.1") }} ... {% endif %}""") >>> b.render(interfaces={'vlan3':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.2.1\n' >>> b.render(interfaces={'vlan1':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.1.1\n'
|
python, templates, dictionary, jinja2, ansible
| 22
| 47,813
| 2
|
https://stackoverflow.com/questions/33400771/check-if-key-exists-in-a-dict-in-jinja2-template-on-ansible
|
35,807,868
|
Ansible: Add Unix group to user only if the group exists
|
I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not exist). Any thoughts on how I might do this with Ansible? Here is my starting point. Command ansible-playbook -i 'localhost,' -c local ansible_user.yml ansible_user.yml --- - hosts: all user: root become: yes vars: password: "!" user: testa tasks: - name: add user user: name="{{user}}" state=present password="{{password}}" shell=/bin/bash append=yes comment="test User" Updated: based on the solution suggested by @udondan, I was able to get this working with the following additional tasks. - name: Check if user exists shell: /usr/bin/getent group | awk -F":" '{print $1}' register: etc_groups - name: Add secondary Groups to user user: name="{{user}}" groups="{{item}}" append=yes when: '"{{item}}" in etc_groups.stdout_lines' with_items: - sudo - wheel
|
Ansible: Add Unix group to user only if the group exists I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not exist). Any thoughts on how I might do this with Ansible? Here is my starting point. Command ansible-playbook -i 'localhost,' -c local ansible_user.yml ansible_user.yml --- - hosts: all user: root become: yes vars: password: "!" user: testa tasks: - name: add user user: name="{{user}}" state=present password="{{password}}" shell=/bin/bash append=yes comment="test User" Updated: based on the solution suggested by @udondan, I was able to get this working with the following additional tasks. - name: Check if user exists shell: /usr/bin/getent group | awk -F":" '{print $1}' register: etc_groups - name: Add secondary Groups to user user: name="{{user}}" groups="{{item}}" append=yes when: '"{{item}}" in etc_groups.stdout_lines' with_items: - sudo - wheel
|
unix, ansible
| 22
| 31,845
| 3
|
https://stackoverflow.com/questions/35807868/ansible-add-unix-group-to-user-only-if-the-group-exists
|
35,185,635
|
Can ansible fetch updated facts in middle of a playbook?
|
I'm having trouble running a full playbook because some of the facts later plays depend on are modified in earlier plays, but ansible doesn't update facts mid-run. Running ansible somehost -m setup when the whole playbook starts against a new VPS: "ansible_selinux": { "status": "disabled" }, My playbook contains a play that installs SELinux and reboots the server (while ansible wait_for's), and a later task uses the conditional when: ansible_selinux.status != 'disabled' . However even though SELinux is now installed and enforcing (which required the reboot) the facts for the system still show SELinux is disabled so that conditional fails and the task is skipped. Running the playbook again of course works because facts are updated and now return: "ansible_selinux": { "config_mode": "enforcing", "mode": "enforcing", "policyvers": 28, "status": "enabled", "type": "targeted" } Is there any way to make facts refresh mid-playbook? Maybe the hack is to set_fact on ansible_selinux.status myself after the reboot? Update : Well that was too easy, thanks to BruceP I added this task to fetch updated facts at the end of my SELinux play - name: SELinux - Force ansible to regather facts setup: filter='ansible_selinux'
|
Can ansible fetch updated facts in middle of a playbook? I'm having trouble running a full playbook because some of the facts later plays depend on are modified in earlier plays, but ansible doesn't update facts mid-run. Running ansible somehost -m setup when the whole playbook starts against a new VPS: "ansible_selinux": { "status": "disabled" }, My playbook contains a play that installs SELinux and reboots the server (while ansible wait_for's), and a later task uses the conditional when: ansible_selinux.status != 'disabled' . However even though SELinux is now installed and enforcing (which required the reboot) the facts for the system still show SELinux is disabled so that conditional fails and the task is skipped. Running the playbook again of course works because facts are updated and now return: "ansible_selinux": { "config_mode": "enforcing", "mode": "enforcing", "policyvers": 28, "status": "enabled", "type": "targeted" } Is there any way to make facts refresh mid-playbook? Maybe the hack is to set_fact on ansible_selinux.status myself after the reboot? Update : Well that was too easy, thanks to BruceP I added this task to fetch updated facts at the end of my SELinux play - name: SELinux - Force ansible to regather facts setup: filter='ansible_selinux'
|
ansible, selinux
| 22
| 20,586
| 2
|
https://stackoverflow.com/questions/35185635/can-ansible-fetch-updated-facts-in-middle-of-a-playbook
|
58,908,625
|
Issue looping on block containing a set of tasks in Ansible
|
I need to check if a file named deploy.db exists. If it does not exist, I need to perform a set of tasks for which I am using a block. Below is how I run the playbook ansible-playbook test.yml \ -e Layer=APP \ -e BASEPATH="/logs" \ -e Filenames="file1,file2,file3" Here is the playbook test.yml : --- - name: "Play 1" hosts: localhost gather_facts: false tasks: - name: Construct debug: msg: "Run" - block: - stat: path="{{ BASEPATH }}/deploy.db" register: currdb - file: path="{{ BASEPATH }}/deploy.db" state=touch recurse=no when: currdb.stat.exists == False - shell: "echo done>>{{ BASEPATH }}/deploy.db" when: currdb.stat.exists == False when: Layer == 'APP' with_items: - "{{ Filenames.split(',') }}" I am getting the below error running the playbook: ERROR! 'with_items' is not a valid attribute for a Block The error appears to be in '/app/test.yml': line 9, column 6, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - block: ^ here After researching a bit, I understand that neither with_items nor loop is supported by a block and the solution is to include a tasks file. I am, however, not sure how to get that to work. Can you suggest what tweaks I need in order to make my playbook work? Considering I am on the latest version of Ansible, are there other solutions?
|
Issue looping on block containing a set of tasks in Ansible I need to check if a file named deploy.db exists. If it does not exist, I need to perform a set of tasks for which I am using a block. Below is how I run the playbook ansible-playbook test.yml \ -e Layer=APP \ -e BASEPATH="/logs" \ -e Filenames="file1,file2,file3" Here is the playbook test.yml : --- - name: "Play 1" hosts: localhost gather_facts: false tasks: - name: Construct debug: msg: "Run" - block: - stat: path="{{ BASEPATH }}/deploy.db" register: currdb - file: path="{{ BASEPATH }}/deploy.db" state=touch recurse=no when: currdb.stat.exists == False - shell: "echo done>>{{ BASEPATH }}/deploy.db" when: currdb.stat.exists == False when: Layer == 'APP' with_items: - "{{ Filenames.split(',') }}" I am getting the below error running the playbook: ERROR! 'with_items' is not a valid attribute for a Block The error appears to be in '/app/test.yml': line 9, column 6, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - block: ^ here After researching a bit, I understand that neither with_items nor loop is supported by a block and the solution is to include a tasks file. I am, however, not sure how to get that to work. Can you suggest what tweaks I need in order to make my playbook work? Considering I am on the latest version of Ansible, are there other solutions?
|
ansible
| 22
| 76,243
| 1
|
https://stackoverflow.com/questions/58908625/issue-looping-on-block-containing-a-set-of-tasks-in-ansible
|
59,938,088
|
Ansible issuing warning about localhost
|
I am running the following ansible playbook - hosts: localhost connection: local vars_files: - vars/config_values.yaml gather_facts: no tasks: - name: Set correct project in gcloud config shell: "gcloud config set project {{ google_project_name }}" Which yields the following warning: [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Given that I am explicitly stating that it will be run against host: localhost , why is it complaining about no inventory being parsed and that the "provided host list is empty"? How to remove these warnings? (without just suppressing them if possible)
|
Ansible issuing warning about localhost I am running the following ansible playbook - hosts: localhost connection: local vars_files: - vars/config_values.yaml gather_facts: no tasks: - name: Set correct project in gcloud config shell: "gcloud config set project {{ google_project_name }}" Which yields the following warning: [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Given that I am explicitly stating that it will be run against host: localhost , why is it complaining about no inventory being parsed and that the "provided host list is empty"? How to remove these warnings? (without just suppressing them if possible)
|
ansible, yaml
| 22
| 88,595
| 4
|
https://stackoverflow.com/questions/59938088/ansible-issuing-warning-about-localhost
|
41,631,770
|
get dict value from variable key in ansible
|
Here is my problem I need to get a dict value from key. But the key is also a var. For example, I had an ansible role. In vars/main.yml , I defined vars as below: --- location: "USA" source: { "China": "/net/server1/patha", "USA": "/net/server2/pathb", "Japan": "/net/server3/pathc" } So in my tasks: tasks/main.yml . How do get "/net/server2/pathb" using the vars. I tried below in tasks, all did not work. -shell: "perl run.perl {{ source.location }}/script.pl" -shell: "perl run.perl {{ source.{{ location }} }}/script.pl" This may be a simple question. But I searched many posts for a long time and still cannot get a right answer. So please help and many thanks.
|
get dict value from variable key in ansible Here is my problem I need to get a dict value from key. But the key is also a var. For example, I had an ansible role. In vars/main.yml , I defined vars as below: --- location: "USA" source: { "China": "/net/server1/patha", "USA": "/net/server2/pathb", "Japan": "/net/server3/pathc" } So in my tasks: tasks/main.yml . How do get "/net/server2/pathb" using the vars. I tried below in tasks, all did not work. -shell: "perl run.perl {{ source.location }}/script.pl" -shell: "perl run.perl {{ source.{{ location }} }}/script.pl" This may be a simple question. But I searched many posts for a long time and still cannot get a right answer. So please help and many thanks.
|
ansible
| 22
| 56,423
| 1
|
https://stackoverflow.com/questions/41631770/get-dict-value-from-variable-key-in-ansible
|
24,126,943
|
Quotes in ansible lineinfile
|
When I use lineinfile in ansible it is not writing ' , " characters lineinfile: 'dest=/home/xyz state=present line="CACHES="default""' it is giving CACHES=default but the desired output is CACHES="default" How to achieve this?
|
Quotes in ansible lineinfile When I use lineinfile in ansible it is not writing ' , " characters lineinfile: 'dest=/home/xyz state=present line="CACHES="default""' it is giving CACHES=default but the desired output is CACHES="default" How to achieve this?
|
ansible
| 22
| 88,639
| 4
|
https://stackoverflow.com/questions/24126943/quotes-in-ansible-lineinfile
|
44,455,240
|
Install pip3 package using ansible instead of pip2
|
I am trying to setup a Django project in vagrant using ansible . I have used the following code for installing the pip packages : - name: Setup Virtualenv pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt I need to use python3 for the django project and even though I have explicitly mentioned to use python3, it is installing the pip packages via pip2 . I have ensured that python3 is installed on the virtual machine. Please, help me install the packages via pip3.
|
Install pip3 package using ansible instead of pip2 I am trying to setup a Django project in vagrant using ansible . I have used the following code for installing the pip packages : - name: Setup Virtualenv pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt I need to use python3 for the django project and even though I have explicitly mentioned to use python3, it is installing the pip packages via pip2 . I have ensured that python3 is installed on the virtual machine. Please, help me install the packages via pip3.
|
django, vagrant, pip, ansible
| 22
| 53,186
| 2
|
https://stackoverflow.com/questions/44455240/install-pip3-package-using-ansible-instead-of-pip2
|
25,918,068
|
Ansible - Can I print information during module execution?
|
I would like to know if there is a way to print information while a module is executing -- primarily as a means to demonstrate that the process is working and has not hung. Specifically, I am trying to get feedback during the execution of the cloudformation module. I tried modifying the (Python) source code to include the following: def debug(msg): print json.dumps({ "DEBUG" : msg }) ... debug("The stack operation is still working...") What this did, of course, was store all this output and only print it all after the module had finished executing. So for particularly large cloudformation templates, this means that I wait around for 5 minutes or so, and then suddenly see a large amount of text appear on the screen at the end. What I was expecting was to see "The stack operation is still working..." printed every x seconds. It would seem that the Asynchronous Actions and Polling are what I'm looking for... but this didn't work, either. The entire task, "Launch CloudFormation for {{ stackname }}", was skipped entirely. See below for the relevant (YAML) snippet from my playbook: - name: Launch CloudFormation for {{ stackname }} cloudformation: > stack_name="{{ stackname }}" state=present region="{{ region }}" disable_rollback=true template="{{ template }}" register: cloud args: template_parameters: KeyName: "{{ keyName }}" Region: "{{ region }}" SecurityGroup: "{{ securityGroup }}" BootStrapper: "{{ bootStrapper }}" BootStrapCommand: "powershell.exe -executionpolicy unrestricted -File C:\\{{ bootStrapper }} {{ region }}" S3Bucket: "{{ s3Bucket }}" async: 3600 poll: 30 This tells me that async is meant for typical shell commands, and not complex modules such as cloudformation. OR -- I may have done something wrong. Could anyone shed some light on this situation? Again, for large cloudformation tasks that take a while, I would like some periodic indication that the task is still running, and not hanging. I appreciate the help!
|
Ansible - Can I print information during module execution? I would like to know if there is a way to print information while a module is executing -- primarily as a means to demonstrate that the process is working and has not hung. Specifically, I am trying to get feedback during the execution of the cloudformation module. I tried modifying the (Python) source code to include the following: def debug(msg): print json.dumps({ "DEBUG" : msg }) ... debug("The stack operation is still working...") What this did, of course, was store all this output and only print it all after the module had finished executing. So for particularly large cloudformation templates, this means that I wait around for 5 minutes or so, and then suddenly see a large amount of text appear on the screen at the end. What I was expecting was to see "The stack operation is still working..." printed every x seconds. It would seem that the Asynchronous Actions and Polling are what I'm looking for... but this didn't work, either. The entire task, "Launch CloudFormation for {{ stackname }}", was skipped entirely. See below for the relevant (YAML) snippet from my playbook: - name: Launch CloudFormation for {{ stackname }} cloudformation: > stack_name="{{ stackname }}" state=present region="{{ region }}" disable_rollback=true template="{{ template }}" register: cloud args: template_parameters: KeyName: "{{ keyName }}" Region: "{{ region }}" SecurityGroup: "{{ securityGroup }}" BootStrapper: "{{ bootStrapper }}" BootStrapCommand: "powershell.exe -executionpolicy unrestricted -File C:\\{{ bootStrapper }} {{ region }}" S3Bucket: "{{ s3Bucket }}" async: 3600 poll: 30 This tells me that async is meant for typical shell commands, and not complex modules such as cloudformation. OR -- I may have done something wrong. Could anyone shed some light on this situation? Again, for large cloudformation tasks that take a while, I would like some periodic indication that the task is still running, and not hanging. I appreciate the help!
|
python, ansible
| 22
| 29,783
| 4
|
https://stackoverflow.com/questions/25918068/ansible-can-i-print-information-during-module-execution
|
27,419,961
|
PostgreSQL fe_sendauth: no password supplied
|
I know there are thousands of questsions like this one here on SO but i've seen them all and i'm still not able to deal with my problem. I'm doing everything using ansible so it's quite automated but, anyway, here are my files: pg_hba.conf local all all trust host all all 127.0.0.1/32 md5 host all all ::1/128 md5 host all all 10.11.12.0/24 md5 database.yml production: database: my_db adapter: postgresql host: localhost username: deploy encoding: unicode min_messages: WARNING template: template0 And i have a deploy user (and postgres user without a password set) in my system created. And now, while i'm totally able to sign in to postgres from bash using psql -d my_db (on server), i'm not able to connect to the db with my rails app. Running rake db:migrateMigration gives me PG::ConnectionBad: fe_sendauth: no password supplied I'm quite terrible at beeing a devop and i'm fighting with that issue from the day before yesterday's morning and it's still here so if there is anyone who can help me with that, i would be be more than grateful.
|
PostgreSQL fe_sendauth: no password supplied I know there are thousands of questsions like this one here on SO but i've seen them all and i'm still not able to deal with my problem. I'm doing everything using ansible so it's quite automated but, anyway, here are my files: pg_hba.conf local all all trust host all all 127.0.0.1/32 md5 host all all ::1/128 md5 host all all 10.11.12.0/24 md5 database.yml production: database: my_db adapter: postgresql host: localhost username: deploy encoding: unicode min_messages: WARNING template: template0 And i have a deploy user (and postgres user without a password set) in my system created. And now, while i'm totally able to sign in to postgres from bash using psql -d my_db (on server), i'm not able to connect to the db with my rails app. Running rake db:migrateMigration gives me PG::ConnectionBad: fe_sendauth: no password supplied I'm quite terrible at beeing a devop and i'm fighting with that issue from the day before yesterday's morning and it's still here so if there is anyone who can help me with that, i would be be more than grateful.
|
postgresql, unix, ansible
| 22
| 64,525
| 2
|
https://stackoverflow.com/questions/27419961/postgresql-fe-sendauth-no-password-supplied
|
21,590,906
|
Using Ansible to download a single file from a private github repo to a remote host
|
Example scenario: config files for a certain service are kept under version control on a private github repo. I want to write a playbook that fetches one of these files on the remote node and puts it into the desired location. I can think of several solutions to this: do a checkout on the machine that runs ansible ( local_action ) and then use the copy module do a checkout on the remote node (with the git module), copy the files to the desired location with command: cp src dest creates=dest (perhaps do this with a handler - only when repo has changes to be pulled) use the url module or command: wget [URL] creates=file in the playbook to only download the file of interest. Is the command module actually going to check if the file to be created is different from the one that may already exist or does it just check the file exists? use wget on the machine that runs ansible ( local_action ) and then use the copy module to push it to the remote node What are the advantages/disadvantages of these. Which (if any) of these could be considered good practice. What is the best general solution to this?
|
Using Ansible to download a single file from a private github repo to a remote host Example scenario: config files for a certain service are kept under version control on a private github repo. I want to write a playbook that fetches one of these files on the remote node and puts it into the desired location. I can think of several solutions to this: do a checkout on the machine that runs ansible ( local_action ) and then use the copy module do a checkout on the remote node (with the git module), copy the files to the desired location with command: cp src dest creates=dest (perhaps do this with a handler - only when repo has changes to be pulled) use the url module or command: wget [URL] creates=file in the playbook to only download the file of interest. Is the command module actually going to check if the file to be created is different from the one that may already exist or does it just check the file exists? use wget on the machine that runs ansible ( local_action ) and then use the copy module to push it to the remote node What are the advantages/disadvantages of these. Which (if any) of these could be considered good practice. What is the best general solution to this?
|
deployment, github, wget, configuration-management, ansible
| 22
| 33,122
| 1
|
https://stackoverflow.com/questions/21590906/using-ansible-to-download-a-single-file-from-a-private-github-repo-to-a-remote-h
|
42,348,098
|
How to create a new partition with Ansible
|
When I run this on the command line it works fine: echo -e "n\np\n1\n\n\nw" | sudo fdisk /dev/sdb But in Ansible it does not want to run in shell: - name: partition new disk shell: echo -e "n\np\n1\n\n\nw" | sudo fdisk /dev/sdb It does not come back with an error, but it does not create the partition either. I checked that Ansible and LVM will not do what I need. Any advice?
|
How to create a new partition with Ansible When I run this on the command line it works fine: echo -e "n\np\n1\n\n\nw" | sudo fdisk /dev/sdb But in Ansible it does not want to run in shell: - name: partition new disk shell: echo -e "n\np\n1\n\n\nw" | sudo fdisk /dev/sdb It does not come back with an error, but it does not create the partition either. I checked that Ansible and LVM will not do what I need. Any advice?
|
bash, ansible, disk-partitioning
| 21
| 48,161
| 5
|
https://stackoverflow.com/questions/42348098/how-to-create-a-new-partition-with-ansible
|
40,086,613
|
Ansible Jinja2 string comparison
|
I am getting value of variable "env" in Jinja2 template file using a variable defined in group_vars like: env: "{{ defined_variable.split('-')[0] }}" env possible three values could be abc , def , xyz . On the basis of this value I want to use server URL, whose possible values I have defined inside defaults/main.yml as: server_abc: [URL] server_def: [URL] server_xyz: [URL] In Jinja2 template, I am trying to do: {% if 'abc' == "{{env}}" %} serverURL: '{{ server_abc }}' {% elif 'def' == "{{env}}" %} serverURL: '{{ server_def}}' {% elif 'xyz' == "{{env}}" %} serverURL: '{{ server_xyz }}' {% else %} ServerURL: 'server Url not found' {% endif %} However it is always ending up defining ServerURL = "server URL not found" even if env comes with value of abc , def or xyz . If I try to replace env in Jinja2 template (hardcoded) like below condition does satisfy to true: {% if 'abc' == "abc" %} serverURL: '{{ server_abc }}' So that implies me syntax is true but the value of "{{env}}" at run time is not evaluated. Any suggestion what can I do to solve this?
|
Ansible Jinja2 string comparison I am getting value of variable "env" in Jinja2 template file using a variable defined in group_vars like: env: "{{ defined_variable.split('-')[0] }}" env possible three values could be abc , def , xyz . On the basis of this value I want to use server URL, whose possible values I have defined inside defaults/main.yml as: server_abc: [URL] server_def: [URL] server_xyz: [URL] In Jinja2 template, I am trying to do: {% if 'abc' == "{{env}}" %} serverURL: '{{ server_abc }}' {% elif 'def' == "{{env}}" %} serverURL: '{{ server_def}}' {% elif 'xyz' == "{{env}}" %} serverURL: '{{ server_xyz }}' {% else %} ServerURL: 'server Url not found' {% endif %} However it is always ending up defining ServerURL = "server URL not found" even if env comes with value of abc , def or xyz . If I try to replace env in Jinja2 template (hardcoded) like below condition does satisfy to true: {% if 'abc' == "abc" %} serverURL: '{{ server_abc }}' So that implies me syntax is true but the value of "{{env}}" at run time is not evaluated. Any suggestion what can I do to solve this?
|
ansible, jinja2, ansible-template
| 21
| 116,253
| 1
|
https://stackoverflow.com/questions/40086613/ansible-jinja2-string-comparison
|
32,703,874
|
Fastest way to gather facts to fact cache
|
I am trying to make Ansible work with --limit and to do that I need facts about other hosts, which I am caching with fact_caching. What command should I run so that it simply gathers all the facts on all the hosts and caches them, without running any tasks? Something like the setup module would be perfect if it cached the facts it gathered, but it seems like it does not.
|
Fastest way to gather facts to fact cache I am trying to make Ansible work with --limit and to do that I need facts about other hosts, which I am caching with fact_caching. What command should I run so that it simply gathers all the facts on all the hosts and caches them, without running any tasks? Something like the setup module would be perfect if it cached the facts it gathered, but it seems like it does not.
|
caching, ansible, ansible-facts
| 21
| 29,648
| 4
|
https://stackoverflow.com/questions/32703874/fastest-way-to-gather-facts-to-fact-cache
|
24,444,964
|
Why I cannot prompt for a variable that will be shared by multiple plays (ansible 1.6.5)
|
I have distilled a playbook that has three plays. The goal is to collect the database password from a prompt in one play and then use the same password in the other two plays. --- - name: database password hosts: - webservers - dbservers vars_prompt: - name: "db_password" prompt: "Enter Database Password for databse user root" default: "root" - hosts: dbservers tasks: - command: echo {{db_password | mandatory }} - hosts: webservers tasks: - command: echo {{db_password | mandatory }} It fails as shown below. Enter Database Password for databse user root [root]: PLAY [database password] ****************************************************** GATHERING FACTS *************************************************************** ok: [vc-dev-1] PLAY [dbservers] ************************************************************** GATHERING FACTS *************************************************************** ok: [vc-dev-1] TASK: [command echo {{db_password | mandatory}}] *************************** fatal: [vc-dev-1] => One or more undefined variables: 'db_password' is undefined FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @.../playbook2.retry vc-dev-1 : ok=3 changed=0 unreachable=1 failed=0
|
Why I cannot prompt for a variable that will be shared by multiple plays (ansible 1.6.5) I have distilled a playbook that has three plays. The goal is to collect the database password from a prompt in one play and then use the same password in the other two plays. --- - name: database password hosts: - webservers - dbservers vars_prompt: - name: "db_password" prompt: "Enter Database Password for databse user root" default: "root" - hosts: dbservers tasks: - command: echo {{db_password | mandatory }} - hosts: webservers tasks: - command: echo {{db_password | mandatory }} It fails as shown below. Enter Database Password for databse user root [root]: PLAY [database password] ****************************************************** GATHERING FACTS *************************************************************** ok: [vc-dev-1] PLAY [dbservers] ************************************************************** GATHERING FACTS *************************************************************** ok: [vc-dev-1] TASK: [command echo {{db_password | mandatory}}] *************************** fatal: [vc-dev-1] => One or more undefined variables: 'db_password' is undefined FATAL: all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @.../playbook2.retry vc-dev-1 : ok=3 changed=0 unreachable=1 failed=0
|
ansible
| 21
| 8,610
| 3
|
https://stackoverflow.com/questions/24444964/why-i-cannot-prompt-for-a-variable-that-will-be-shared-by-multiple-plays-ansibl
|
56,313,083
|
Ansible + Ubuntu 18.04 + MySQL = "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required."
|
Iβm seeing the above message on multiple playbooks using Ansible 2.8 on Ubuntu 18.04. In the interests of simplicity Iβve reproduced it using this basic playbook for a single node Drupal server. [URL] ; this playbook works fine on earlier versions of ubuntu, but not on 18.04 which I understand includes python3 by default. Iβve used vagrant to create the base machine, which shows the following: $ which python /usr/bin/python $ which python2 /usr/bin/python2 $ which python3 /usr/bin/python3 $ python --version Python 2.7.15rc1 $ python2 --version Python 2.7.15rc1 $ python3 --version Python 3.6.7 Which seems to be telling me that both python 2 and python 3 are installed, but that 2.7 is the default as that is what responds to $ python --version. I have tried all the suggestions described in this article: [URL] Including specifying the ansible_python_interpreter=/usr/bin/python3 But nothing affects the message. The edited -vvv output from the playbook run is below. Has anyone got any more ideas about either the problem or solution. TASK [Remove the MySQL test database.] **************************************************************************************************************************** task path: /vagrant/provisioning/playbook.yml:96 <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o . . . Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/database/mysql/mysql_db.py <10.1.1.11> PUT /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH TO /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151793 1/AnsiballZ_mysql_db.py <10.1.1.11> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthent ication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout= 10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 '[10.1.1.11]' <10.1.1.11> (0, 'sftp> put /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836 381517931/AnsiballZ_mysql_db.py\n', '') <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'chmod u+x /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-1668363815 17931/ /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py && sleep 0'"'"'' <10.1.1.11> (0, '', '') <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 -tt 10.1.1.11 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-qwjewg qckuyapsxnkbqoegainrkyiinc ; /usr/bin/python3 /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py'"'"'"'"'"'"'"'"' & & sleep 0'"'"'' <10.1.1.11> (1, 'BECOME-SUCCESS-qwjewgqckuyapsxnkbqoegainrkyiinc\r\n\r\n{"msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is req uired.", "failed": true, "invocation": {"module_args": {"db": "test", "state": "absent", "name": "test", "login_host": "localhost", "login_port": 3306, "encoding": "", "collation": "", "connect_timeout": 30, "config_file": "/root/.my.cnf", "single_transaction": false, "quick": true, "ignore_tables": [], "login_user": null, " login_password": null, "login_unix_socket": null, "target": null, "client_cert": null, "client_key": null, "ca_cert": null}}}\r\n', 'Shared connection to 10.1.1.11 closed.\r\n') <10.1.1.11> Failed to connect to the host via ssh: Shared connection to 10.1.1.11 closed. <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'rm -f -r /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151 7931/ > /dev/null 2>&1 && sleep 0'"'"'' <10.1.1.11> (0, '', '')
|
Ansible + Ubuntu 18.04 + MySQL = "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required." Iβm seeing the above message on multiple playbooks using Ansible 2.8 on Ubuntu 18.04. In the interests of simplicity Iβve reproduced it using this basic playbook for a single node Drupal server. [URL] ; this playbook works fine on earlier versions of ubuntu, but not on 18.04 which I understand includes python3 by default. Iβve used vagrant to create the base machine, which shows the following: $ which python /usr/bin/python $ which python2 /usr/bin/python2 $ which python3 /usr/bin/python3 $ python --version Python 2.7.15rc1 $ python2 --version Python 2.7.15rc1 $ python3 --version Python 3.6.7 Which seems to be telling me that both python 2 and python 3 are installed, but that 2.7 is the default as that is what responds to $ python --version. I have tried all the suggestions described in this article: [URL] Including specifying the ansible_python_interpreter=/usr/bin/python3 But nothing affects the message. The edited -vvv output from the playbook run is below. Has anyone got any more ideas about either the problem or solution. TASK [Remove the MySQL test database.] **************************************************************************************************************************** task path: /vagrant/provisioning/playbook.yml:96 <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o . . . Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/database/mysql/mysql_db.py <10.1.1.11> PUT /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH TO /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151793 1/AnsiballZ_mysql_db.py <10.1.1.11> SSH: EXEC sftp -b - -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthent ication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout= 10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 '[10.1.1.11]' <10.1.1.11> (0, 'sftp> put /home/mt-tools-user/.ansible/tmp/ansible-local-21287bh5dK5/tmp7pOKOH /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836 381517931/AnsiballZ_mysql_db.py\n', '') <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'chmod u+x /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-1668363815 17931/ /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py && sleep 0'"'"'' <10.1.1.11> (0, '', '') <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 -tt 10.1.1.11 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-qwjewg qckuyapsxnkbqoegainrkyiinc ; /usr/bin/python3 /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-166836381517931/AnsiballZ_mysql_db.py'"'"'"'"'"'"'"'"' & & sleep 0'"'"'' <10.1.1.11> (1, 'BECOME-SUCCESS-qwjewgqckuyapsxnkbqoegainrkyiinc\r\n\r\n{"msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is req uired.", "failed": true, "invocation": {"module_args": {"db": "test", "state": "absent", "name": "test", "login_host": "localhost", "login_port": 3306, "encoding": "", "collation": "", "connect_timeout": 30, "config_file": "/root/.my.cnf", "single_transaction": false, "quick": true, "ignore_tables": [], "login_user": null, " login_password": null, "login_unix_socket": null, "target": null, "client_cert": null, "client_key": null, "ca_cert": null}}}\r\n', 'Shared connection to 10.1.1.11 closed.\r\n') <10.1.1.11> Failed to connect to the host via ssh: Shared connection to 10.1.1.11 closed. <10.1.1.11> ESTABLISH SSH CONNECTION FOR USER: mt-ansible-user <10.1.1.11> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o 'IdentityFile="/home/mt-tools-user/.ssh/mt_ansible_rsa"' -o KbdInteractiveAuthenticatio n=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="mt-ansible-user"' -o ConnectTimeout=10 -o ControlPath=/home/mt-tools-user/.ansible/cp/af4de51057 10.1.1.11 '/bin/sh -c '"'"'rm -f -r /home/mt-ansible-user/.ansible/tmp/ansible-tmp-1558868136.49-16683638151 7931/ > /dev/null 2>&1 && sleep 0'"'"'' <10.1.1.11> (0, '', '')
|
python, mysql, ansible
| 21
| 35,614
| 3
|
https://stackoverflow.com/questions/56313083/ansible-ubuntu-18-04-mysql-the-pymysql-python-2-7-and-python-3-x-or-mys
|
40,496,021
|
How to remove a single key from an Ansible dictionary?
|
I'd like to remove a single key from a dictionary in Ansible. For example, I'd like this: - debug: var=dict2 vars: dict: a: 1 b: 2 c: 3 dict2: "{{ dict | filter_to_remove_key('a') }}" To print this: ok: [localhost] => { "dict2": { "b": 2, "c": 3 } } Please note that the dictionary is loaded from a json file and I POST it to the Grafana REST API. I'd like to allow saving an 'id' key in the file and remove the key before POSTing it. This is closer to the actual use I have for the removal: - name: Install Dashboards uri: url: "{{ grafana_api_url }}/dashboards/db" method: POST headers: Authorization: Bearer {{ grafana_api_token }} body: overwrite: true dashboard: "{{ lookup('file', item) | from_json | removekey('id') }}" body_format: json with_fileglob: - "dashboards/*.json" - "../../../dashboards/*.json"
|
How to remove a single key from an Ansible dictionary? I'd like to remove a single key from a dictionary in Ansible. For example, I'd like this: - debug: var=dict2 vars: dict: a: 1 b: 2 c: 3 dict2: "{{ dict | filter_to_remove_key('a') }}" To print this: ok: [localhost] => { "dict2": { "b": 2, "c": 3 } } Please note that the dictionary is loaded from a json file and I POST it to the Grafana REST API. I'd like to allow saving an 'id' key in the file and remove the key before POSTing it. This is closer to the actual use I have for the removal: - name: Install Dashboards uri: url: "{{ grafana_api_url }}/dashboards/db" method: POST headers: Authorization: Bearer {{ grafana_api_token }} body: overwrite: true dashboard: "{{ lookup('file', item) | from_json | removekey('id') }}" body_format: json with_fileglob: - "dashboards/*.json" - "../../../dashboards/*.json"
|
dictionary, ansible
| 21
| 28,278
| 7
|
https://stackoverflow.com/questions/40496021/how-to-remove-a-single-key-from-an-ansible-dictionary
|
25,981,863
|
Using failed_when on a with_items task depending on return codes
|
I am trying to write a task which runs a list of ldapmodify statements and only want it to fail if any of the return codes are not 0 or 68 (object allready existed): - name: add needed LDAP infrastructure action: command ldapmodify -x -D '{{ ADMINDN }}' -w '{{ LDAPPW }}' -H {{ LDAPURI }} -c -f {{ item }} register: result failed_when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" # ignore_errors: true with_items: - a.ldif - b.ldif Does not work, producing the error: error while evaluating conditional: result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0 However if I comment the failed_when and use ignore_errors , the following tasks produce the correct results. While I can use this workaround to solve my problem, I would like to understand why the failed_when version is not working, as I would find that more elegant. - debug: var="result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" - fail: msg="failure during ldapmodify" when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" Sidenote sameas might be equalto in other versions of jinja2, in case you are wondering.
|
Using failed_when on a with_items task depending on return codes I am trying to write a task which runs a list of ldapmodify statements and only want it to fail if any of the return codes are not 0 or 68 (object allready existed): - name: add needed LDAP infrastructure action: command ldapmodify -x -D '{{ ADMINDN }}' -w '{{ LDAPPW }}' -H {{ LDAPURI }} -c -f {{ item }} register: result failed_when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" # ignore_errors: true with_items: - a.ldif - b.ldif Does not work, producing the error: error while evaluating conditional: result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0 However if I comment the failed_when and use ignore_errors , the following tasks produce the correct results. While I can use this workaround to solve my problem, I would like to understand why the failed_when version is not working, as I would find that more elegant. - debug: var="result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" - fail: msg="failure during ldapmodify" when: "result.results | rejectattr('rc', 'sameas', 0) | rejectattr('rc', 'sameas', 68) | list | length > 0" Sidenote sameas might be equalto in other versions of jinja2, in case you are wondering.
|
ansible
| 21
| 21,667
| 1
|
https://stackoverflow.com/questions/25981863/using-failed-when-on-a-with-items-task-depending-on-return-codes
|
47,994,497
|
How to pipe commands using Ansible? e.g. curl -sL host.com | sudo bash -
|
I want to make the command via Ansible: curl -sL [URL] | sudo bash - How can I do it via Ansible? Now I have: - name: Add repository command: curl -sL [URL] | sudo bash - But it throw error: [WARNING]: Consider using get_url or uri module rather than running curl fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ["curl", "-sL", "[URL] "|", "sudo", "bash", "-"], "delta": "0:00:00.006202", "end": "2017-12-27 15:11:55.441754", "msg": "non-zero return code", "rc": 2, "start": "2017-12-27 15:11:55.435552", "stderr": "curl: option -: is unknown\ncurl: try 'curl --help' or 'curl --manual' for more information", "stderr_lines": ["curl: option -: is unknown", "curl: try 'curl --help' or 'curl --manual' for more information"], "stdout": "", "stdout_lines": []}
|
How to pipe commands using Ansible? e.g. curl -sL host.com | sudo bash - I want to make the command via Ansible: curl -sL [URL] | sudo bash - How can I do it via Ansible? Now I have: - name: Add repository command: curl -sL [URL] | sudo bash - But it throw error: [WARNING]: Consider using get_url or uri module rather than running curl fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ["curl", "-sL", "[URL] "|", "sudo", "bash", "-"], "delta": "0:00:00.006202", "end": "2017-12-27 15:11:55.441754", "msg": "non-zero return code", "rc": 2, "start": "2017-12-27 15:11:55.435552", "stderr": "curl: option -: is unknown\ncurl: try 'curl --help' or 'curl --manual' for more information", "stderr_lines": ["curl: option -: is unknown", "curl: try 'curl --help' or 'curl --manual' for more information"], "stdout": "", "stdout_lines": []}
|
ansible, pipe
| 21
| 22,944
| 3
|
https://stackoverflow.com/questions/47994497/how-to-pipe-commands-using-ansible-e-g-curl-sl-host-com-sudo-bash
|
37,756,586
|
Loop dictionary in ansible template
|
I'm trying to loop a dictionary through an ansible template using jinja2 to create a number of datasources but receive this error [{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'value'", 'failed': True}]} When running a debug task it does get the correct values back so I feel like my issue is in the template itself but I've been unable to figure out what I am doing wrong. Ansible Task - name: debug dictionary debug: msg="{{ item.value.db_url }}" with_dict: databases - name: copy tomcat config files template: src="{{ item.src }}" dest="{{ item.dest }}" with_items: - { src: 'context.xml.j2', dest: '/opt/tomcat/conf/context.xml'} notify: restart tomcat with_dict: databases Ansible Dictionary databases: db1: db_resource: jdbc/db1 db_maxidle: 50 db_maxconn: 350 db_maxwait: 10000 db_user: dbuser db_pass: "{{ dbpass }}" db_url: jdbc:postgresql://server:5432/dbname db_driver: org.postgresql.Driver Jinja2 Template {% for items in databases %} <resource name="{{ item.value.db_resource }}" auth="container" type="javax.sql.datasource" maxtotal="{{ item.value.db_maxconn }}" maxidle="{{ item.value.db_maxidle }}" maxwaitmillis="{{ item.value.db_maxwait }}" username="{{ item.value.db_user }}" password="{{ item.value.db_pass }}" driverclassname="{{ item.value.db_driver }}" url="{{ item.value.db_url }}" /> {% endfor %} Debug Output ok: [IP] => (item={'key': 'db1', 'value': {'db_maxwait': 10000, 'db_maxconn': 350, 'db_maxidle': 50, 'db_driver': 'org.postgresql.Driver', 'db_pass': u'REDACTED', 'db_resource': 'jdbc/db1', 'db_user': 'dbuser', 'db_url': 'jdbc:postgresql://server:5432/dbname'}}) => { "item": { "key": "db1", "value": { "db_driver": "org.postgresql.Driver", "db_maxconn": 350, "db_maxidle": 50, "db_maxwait": 10000, "db_pass": "REDACTED", "db_resource": "jdbc/db1", "db_url": "jdbc:postgresql://server:5432/db", "db_user": "dbuser" } }, "msg": "jdbc:postgresql://server:5432/dbname" }
|
Loop dictionary in ansible template I'm trying to loop a dictionary through an ansible template using jinja2 to create a number of datasources but receive this error [{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'value'", 'failed': True}]} When running a debug task it does get the correct values back so I feel like my issue is in the template itself but I've been unable to figure out what I am doing wrong. Ansible Task - name: debug dictionary debug: msg="{{ item.value.db_url }}" with_dict: databases - name: copy tomcat config files template: src="{{ item.src }}" dest="{{ item.dest }}" with_items: - { src: 'context.xml.j2', dest: '/opt/tomcat/conf/context.xml'} notify: restart tomcat with_dict: databases Ansible Dictionary databases: db1: db_resource: jdbc/db1 db_maxidle: 50 db_maxconn: 350 db_maxwait: 10000 db_user: dbuser db_pass: "{{ dbpass }}" db_url: jdbc:postgresql://server:5432/dbname db_driver: org.postgresql.Driver Jinja2 Template {% for items in databases %} <resource name="{{ item.value.db_resource }}" auth="container" type="javax.sql.datasource" maxtotal="{{ item.value.db_maxconn }}" maxidle="{{ item.value.db_maxidle }}" maxwaitmillis="{{ item.value.db_maxwait }}" username="{{ item.value.db_user }}" password="{{ item.value.db_pass }}" driverclassname="{{ item.value.db_driver }}" url="{{ item.value.db_url }}" /> {% endfor %} Debug Output ok: [IP] => (item={'key': 'db1', 'value': {'db_maxwait': 10000, 'db_maxconn': 350, 'db_maxidle': 50, 'db_driver': 'org.postgresql.Driver', 'db_pass': u'REDACTED', 'db_resource': 'jdbc/db1', 'db_user': 'dbuser', 'db_url': 'jdbc:postgresql://server:5432/dbname'}}) => { "item": { "key": "db1", "value": { "db_driver": "org.postgresql.Driver", "db_maxconn": 350, "db_maxidle": 50, "db_maxwait": 10000, "db_pass": "REDACTED", "db_resource": "jdbc/db1", "db_url": "jdbc:postgresql://server:5432/db", "db_user": "dbuser" } }, "msg": "jdbc:postgresql://server:5432/dbname" }
|
ansible, jinja2, ansible-template
| 21
| 73,907
| 5
|
https://stackoverflow.com/questions/37756586/loop-dictionary-in-ansible-template
|
32,748,585
|
SSH into a Vagrant machine with Ansible
|
Normally, you can ssh into a Vagrant-managed VM with vagrant ssh . There are two options: You can use an insecure_private_key generated by Vagrant to authenticate. Use your own private key - provided that config.ssh.forward_agent is set to true , and the VM is configured correctly I use the second option. S when I run vagrant ssh , I ssh into the machine with my custom private key. Now I need to let Ansible SSH into my Vagrant machine and I do not want to use Vagrantfile for it. So I executed: ansible-playbook -i hosts/development --private-key=~/.ssh/id_rsa -u vagrant dev.yml And I have this error returned: fatal: [192.168.50.5] => SSH Error: Permission denied (publickey). while connecting to 192.168.50.5:22 The hosts/inventory file holds just the IP of my Vagrant VM (192.168.50.5). I do not know why Ansible cannot ssh into the VM. It's using exactly the same user ( vagrant ) and key ( id_rsa ) as when executing vagrant ssh . However, there is no problem sshing with vagrant ssh while the above would not run. Any suggestions would be much appreciated.
|
SSH into a Vagrant machine with Ansible Normally, you can ssh into a Vagrant-managed VM with vagrant ssh . There are two options: You can use an insecure_private_key generated by Vagrant to authenticate. Use your own private key - provided that config.ssh.forward_agent is set to true , and the VM is configured correctly I use the second option. S when I run vagrant ssh , I ssh into the machine with my custom private key. Now I need to let Ansible SSH into my Vagrant machine and I do not want to use Vagrantfile for it. So I executed: ansible-playbook -i hosts/development --private-key=~/.ssh/id_rsa -u vagrant dev.yml And I have this error returned: fatal: [192.168.50.5] => SSH Error: Permission denied (publickey). while connecting to 192.168.50.5:22 The hosts/inventory file holds just the IP of my Vagrant VM (192.168.50.5). I do not know why Ansible cannot ssh into the VM. It's using exactly the same user ( vagrant ) and key ( id_rsa ) as when executing vagrant ssh . However, there is no problem sshing with vagrant ssh while the above would not run. Any suggestions would be much appreciated.
|
ssh, vagrant, ansible
| 21
| 21,250
| 4
|
https://stackoverflow.com/questions/32748585/ssh-into-a-vagrant-machine-with-ansible
|
28,754,155
|
Ansible Do Task If Apt Package Is Missing
|
I'm looking to do a series of tasks if a specific apt package is missing. for example: if graphite-carbon is NOT installed do: - apt: name=debconf-utils state=present - shell: echo 'graphite-carbon/postrm_remove_databases boolean false' | debconf-set-selections - apt: name=debconf-utils state=absent another example: if statsd is NOT installed do: - file: path=/tmp/build state=directory - shell: cd /tmp/build ; git clone [URL] ; cd statsd ; dpkg-buildpackage - shell: dpkg -i /tmp/build/statsd*.deb How would I begin to crack this? I'm thinking maybe I can do a -shell: dpkg -l|grep <package name> and capture the return code somehow.
|
Ansible Do Task If Apt Package Is Missing I'm looking to do a series of tasks if a specific apt package is missing. for example: if graphite-carbon is NOT installed do: - apt: name=debconf-utils state=present - shell: echo 'graphite-carbon/postrm_remove_databases boolean false' | debconf-set-selections - apt: name=debconf-utils state=absent another example: if statsd is NOT installed do: - file: path=/tmp/build state=directory - shell: cd /tmp/build ; git clone [URL] ; cd statsd ; dpkg-buildpackage - shell: dpkg -i /tmp/build/statsd*.deb How would I begin to crack this? I'm thinking maybe I can do a -shell: dpkg -l|grep <package name> and capture the return code somehow.
|
conditional-statements, apt, ansible
| 21
| 27,196
| 4
|
https://stackoverflow.com/questions/28754155/ansible-do-task-if-apt-package-is-missing
|
27,805,976
|
resolve dictionary key or parameter variable in Ansible
|
In Ansible, if I try to use a variable as a parameter name, or a key name, it is never resolved. For example, if I have {{ some_var }}: true , or: template: "{{ resolve_me_to_src }}": "some_src" the variables will just be used literally and never resolve. My specific use case is using this with the ec2 module, where some of my tag names are stored as variables: - name: Provision a set of instances ec2: group: "{{ aws_security_group }}" instance_type: "{{ aws_instance_type }}" image: "{{ aws_ami_id }}" region: "{{ aws_region }}" vpc_subnet_id: "{{ aws_vpc_subnet_id }}" key_name: "{{ aws_key_name }}" wait: true count: "{{ num_machines }}" instance_tags: { "{{ some_tag }}": "{{ some_value }}", "{{ other_tag }}": "{{ other_value }}" } Is there any way around this? Can I mark that I want to force evaluation somehow?
|
resolve dictionary key or parameter variable in Ansible In Ansible, if I try to use a variable as a parameter name, or a key name, it is never resolved. For example, if I have {{ some_var }}: true , or: template: "{{ resolve_me_to_src }}": "some_src" the variables will just be used literally and never resolve. My specific use case is using this with the ec2 module, where some of my tag names are stored as variables: - name: Provision a set of instances ec2: group: "{{ aws_security_group }}" instance_type: "{{ aws_instance_type }}" image: "{{ aws_ami_id }}" region: "{{ aws_region }}" vpc_subnet_id: "{{ aws_vpc_subnet_id }}" key_name: "{{ aws_key_name }}" wait: true count: "{{ num_machines }}" instance_tags: { "{{ some_tag }}": "{{ some_value }}", "{{ other_tag }}": "{{ other_value }}" } Is there any way around this? Can I mark that I want to force evaluation somehow?
|
ansible
| 21
| 18,399
| 2
|
https://stackoverflow.com/questions/27805976/resolve-dictionary-key-or-parameter-variable-in-ansible
|
42,935,820
|
Ansible, set_fact using if then else statement
|
I am trying to set a variable in Ansible with set_fact at runtime based upon another variable. If uses first value no matter what the actual value is. Here is my code example: - name: Global_vars - get date info set_fact: jm_env: "{{lookup('env', 'Environment')}}" l_env: "{% if '{{jm_env}}==Develop' %}d{% elif '{{jm_env}}==Staging'%}s{% else %}p{% endif %}" l_env is d no matter what jm_env is set.
|
Ansible, set_fact using if then else statement I am trying to set a variable in Ansible with set_fact at runtime based upon another variable. If uses first value no matter what the actual value is. Here is my code example: - name: Global_vars - get date info set_fact: jm_env: "{{lookup('env', 'Environment')}}" l_env: "{% if '{{jm_env}}==Develop' %}d{% elif '{{jm_env}}==Staging'%}s{% else %}p{% endif %}" l_env is d no matter what jm_env is set.
|
ansible, jinja2, ansible-template
| 21
| 62,321
| 2
|
https://stackoverflow.com/questions/42935820/ansible-set-fact-using-if-then-else-statement
|
24,112,066
|
ansible: Is there something like with_fileglobs for files on remote machine?
|
I'm trying to turn these lines into something I can put in an ansible playbook: # Install Prezto files shopt -s extglob shopt -s nullglob files=( "${ZDOTDIR:-$HOME}"/.zprezto/runcoms/!(README.md) ) for rcfile in "${files[@]}"; do [[ -f $rcfile ]] && ln -s "$rcfile" "${ZDOTDIR:-$HOME}/.${rcfile##*/}" done So far I've got the following: - name: Link Prezto files file: src={{ item }} dest=~ state=link with_fileglob: - ~/.zprezto/runcoms/z* I know it isn't the same, but it would select the same files: except with_fileglob looks on the host machine, and I want it to look on the remote machine. Is there any way to do this, or should I just use a shell script?
|
ansible: Is there something like with_fileglobs for files on remote machine? I'm trying to turn these lines into something I can put in an ansible playbook: # Install Prezto files shopt -s extglob shopt -s nullglob files=( "${ZDOTDIR:-$HOME}"/.zprezto/runcoms/!(README.md) ) for rcfile in "${files[@]}"; do [[ -f $rcfile ]] && ln -s "$rcfile" "${ZDOTDIR:-$HOME}/.${rcfile##*/}" done So far I've got the following: - name: Link Prezto files file: src={{ item }} dest=~ state=link with_fileglob: - ~/.zprezto/runcoms/z* I know it isn't the same, but it would select the same files: except with_fileglob looks on the host machine, and I want it to look on the remote machine. Is there any way to do this, or should I just use a shell script?
|
bash, shell, ansible
| 21
| 11,204
| 4
|
https://stackoverflow.com/questions/24112066/ansible-is-there-something-like-with-fileglobs-for-files-on-remote-machine
|
40,606,890
|
How to share group_vars between different inventories in Ansible?
|
The Ansible best practices documentation recommends to separate inventories: inventories/ production/ hosts.ini # inventory file for production servers group_vars/ group1 # here we assign variables to particular groups group2 # "" host_vars/ hostname1 # if systems need specific variables, put them here hostname2 # "" staging/ hosts.ini # inventory file for staging environment group_vars/ group1 # here we assign variables to particular groups group2 # "" host_vars/ stagehost1 # if systems need specific variables, put them here stagehost2 # "" My staging and production environments are structured in the same way. I have in both environments the same groups. And it turns out that I have also the same group_vars for the same groups. This means redundancy I would like to wipe out. Is there a way to share some group_vars between different inventories? As a work-around I started to put shared group_vars into the roles. my_var: my_group: - { var1: 1, var2: 2 } This makes it possible to iterate over some vars by intersecting the groups of a host with the defined var: with_items: "{{group_names | intersect(my_var.keys())}}" But this is a bit complicate to understand and I think roles should not know anything about groups. I would like to separate most of the inventories but share some of the group_vars in an easy to understand way. Is it possible to merge global group_vars with inventory specific group_vars?
|
How to share group_vars between different inventories in Ansible? The Ansible best practices documentation recommends to separate inventories: inventories/ production/ hosts.ini # inventory file for production servers group_vars/ group1 # here we assign variables to particular groups group2 # "" host_vars/ hostname1 # if systems need specific variables, put them here hostname2 # "" staging/ hosts.ini # inventory file for staging environment group_vars/ group1 # here we assign variables to particular groups group2 # "" host_vars/ stagehost1 # if systems need specific variables, put them here stagehost2 # "" My staging and production environments are structured in the same way. I have in both environments the same groups. And it turns out that I have also the same group_vars for the same groups. This means redundancy I would like to wipe out. Is there a way to share some group_vars between different inventories? As a work-around I started to put shared group_vars into the roles. my_var: my_group: - { var1: 1, var2: 2 } This makes it possible to iterate over some vars by intersecting the groups of a host with the defined var: with_items: "{{group_names | intersect(my_var.keys())}}" But this is a bit complicate to understand and I think roles should not know anything about groups. I would like to separate most of the inventories but share some of the group_vars in an easy to understand way. Is it possible to merge global group_vars with inventory specific group_vars?
|
ansible
| 21
| 15,560
| 3
|
https://stackoverflow.com/questions/40606890/how-to-share-group-vars-between-different-inventories-in-ansible
|
28,963,751
|
Ansible write variables into YAML file
|
I have a specific ansible variable structure that I want to get from the vault into a yaml file on my hosts. Lets assume a structure like this: secrets: psp1: username: this password: that secret_key: 123 ... I need something like a "generic" template to output whatever "secrets" contains at the moment, since the content changes almost completely based on the current environment. The easiest solution I can think of is to output the whole structure in an template like this: # config/secrets.yml {{ secrets | to_yaml }} But the jinja2 to_yaml filter does only "yamlify" the first level, deeper nestings are outputted in json. Can I work around that problem somehow? Is there an easier way to achieve what I want? Thanks for any help!
|
Ansible write variables into YAML file I have a specific ansible variable structure that I want to get from the vault into a yaml file on my hosts. Lets assume a structure like this: secrets: psp1: username: this password: that secret_key: 123 ... I need something like a "generic" template to output whatever "secrets" contains at the moment, since the content changes almost completely based on the current environment. The easiest solution I can think of is to output the whole structure in an template like this: # config/secrets.yml {{ secrets | to_yaml }} But the jinja2 to_yaml filter does only "yamlify" the first level, deeper nestings are outputted in json. Can I work around that problem somehow? Is there an easier way to achieve what I want? Thanks for any help!
|
python, yaml, jinja2, ansible
| 21
| 43,503
| 1
|
https://stackoverflow.com/questions/28963751/ansible-write-variables-into-yaml-file
|
41,379,083
|
Sourcing a file before executing commands in Ansible
|
I am trying to install node js version using nvm using below Ansible yml file. I get error like source "source /home/centos/.nvm/nvm.sh" file not found. But if I do the same by logging into the machine using ssh then it works fine. - name: Install nvm git: repo=[URL] dest=~/.nvm version={{ nvm.version }} tags: nvm - name: Source nvm in ~/.profile lineinfile: > dest=~/.profile line="source ~/.nvm/nvm.sh" create=yes tags: nvm - name: Install node {{ nvm.node_version }} command: "{{ item }}" with_items: - "source /home/centos/.nvm/nvm.sh" - nvm install {{ nvm.node_version }} tags: nvm Error: failed: [172.29.4.71] (item=source /home/centos/.nvm/nvm.sh) => {"cmd": "source /home/centos/.nvm/nvm.sh", "failed": true, "item": "source /home/centos/.nvm/nvm.sh", "msg": "[Errno 2] No such file or directory", "rc": 2} failed: [172.29.4.71] (item=nvm install 6.2.0) => {"cmd": "nvm install 6.2.0", "failed": true, "item": "nvm install 6.2.0", "msg": "[Errno 2] No such file or directory", "rc": 2}
|
Sourcing a file before executing commands in Ansible I am trying to install node js version using nvm using below Ansible yml file. I get error like source "source /home/centos/.nvm/nvm.sh" file not found. But if I do the same by logging into the machine using ssh then it works fine. - name: Install nvm git: repo=[URL] dest=~/.nvm version={{ nvm.version }} tags: nvm - name: Source nvm in ~/.profile lineinfile: > dest=~/.profile line="source ~/.nvm/nvm.sh" create=yes tags: nvm - name: Install node {{ nvm.node_version }} command: "{{ item }}" with_items: - "source /home/centos/.nvm/nvm.sh" - nvm install {{ nvm.node_version }} tags: nvm Error: failed: [172.29.4.71] (item=source /home/centos/.nvm/nvm.sh) => {"cmd": "source /home/centos/.nvm/nvm.sh", "failed": true, "item": "source /home/centos/.nvm/nvm.sh", "msg": "[Errno 2] No such file or directory", "rc": 2} failed: [172.29.4.71] (item=nvm install 6.2.0) => {"cmd": "nvm install 6.2.0", "failed": true, "item": "nvm install 6.2.0", "msg": "[Errno 2] No such file or directory", "rc": 2}
|
ansible
| 21
| 22,754
| 1
|
https://stackoverflow.com/questions/41379083/sourcing-a-file-before-executing-commands-in-ansible
|
45,400,851
|
Concat multiple variables and strings in ansible playbook
|
I'm trying multiple concatenation when preforming with_items for the destination section. Right now it looks like this: - name: create app except+lookup copy: content="" dest="{{ dir.comp ~ '/config/con2dd/' ~ item.name ~ 'File.txt' }}" force=no group=devops owner=devops mode: 0755 with_items: ... I get: We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" Tried couple of approaches but none resulted something that's working. Is it possible to concat the variables with the strings?
|
Concat multiple variables and strings in ansible playbook I'm trying multiple concatenation when preforming with_items for the destination section. Right now it looks like this: - name: create app except+lookup copy: content="" dest="{{ dir.comp ~ '/config/con2dd/' ~ item.name ~ 'File.txt' }}" force=no group=devops owner=devops mode: 0755 with_items: ... I get: We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" Tried couple of approaches but none resulted something that's working. Is it possible to concat the variables with the strings?
|
ansible, concatenation, yaml
| 21
| 67,701
| 2
|
https://stackoverflow.com/questions/45400851/concat-multiple-variables-and-strings-in-ansible-playbook
|
47,414,988
|
How to run only one role of an Ansible playbook?
|
I have a site.yml which imports several playbooks. - import_playbook: webservers.yml - .... Every playbook "calls" several roles: - name: apply the webserver configuration hosts: webservers roles: - javajdk - tomcat - apache How can I run only the javajdk role ? This would run all roles... ansible-playbook -i inventory webservers.yml I know that there are tags , but how do I assign them to a role in general?
|
How to run only one role of an Ansible playbook? I have a site.yml which imports several playbooks. - import_playbook: webservers.yml - .... Every playbook "calls" several roles: - name: apply the webserver configuration hosts: webservers roles: - javajdk - tomcat - apache How can I run only the javajdk role ? This would run all roles... ansible-playbook -i inventory webservers.yml I know that there are tags , but how do I assign them to a role in general?
|
ansible, ansible-2.x, ansible-role
| 21
| 47,154
| 2
|
https://stackoverflow.com/questions/47414988/how-to-run-only-one-role-of-an-ansible-playbook
|
66,335,800
|
ERROR! couldn't resolve module/action . This often indicates a misspelling, missing collection, or incorrect module path
|
I've got an Ansible Collections in my Ansible playbook as follows: - name: Create a profile for the user community.windows.win_user_profile: username: test name: test state: present and the collection is installed via ansible-galaxy collection install ansible.windows so I can see it at ~/.ansible/collections. However I keep getting: ERROR! couldn't resolve module/action 'community.windows.win_user_profile'. This often indicates a misspelling, missing collection, or incorrect module path. I've also copied it alongside the playbook just in case but still get the same error message. Any suggestions?
|
ERROR! couldn't resolve module/action . This often indicates a misspelling, missing collection, or incorrect module path I've got an Ansible Collections in my Ansible playbook as follows: - name: Create a profile for the user community.windows.win_user_profile: username: test name: test state: present and the collection is installed via ansible-galaxy collection install ansible.windows so I can see it at ~/.ansible/collections. However I keep getting: ERROR! couldn't resolve module/action 'community.windows.win_user_profile'. This often indicates a misspelling, missing collection, or incorrect module path. I've also copied it alongside the playbook just in case but still get the same error message. Any suggestions?
|
ansible
| 21
| 141,268
| 6
|
https://stackoverflow.com/questions/66335800/error-couldnt-resolve-module-action-this-often-indicates-a-misspelling-miss
|
27,661,414
|
SSH to remote server using ansible
|
I'm using ansible to automate some tasks. One of those requires me to ssh to server A, then to B from A and then to C from B. I can't seem to find any way to get ansible to do that. Any suggestions?
|
SSH to remote server using ansible I'm using ansible to automate some tasks. One of those requires me to ssh to server A, then to B from A and then to C from B. I can't seem to find any way to get ansible to do that. Any suggestions?
|
ssh, ansible
| 21
| 20,172
| 2
|
https://stackoverflow.com/questions/27661414/ssh-to-remote-server-using-ansible
|
37,479,605
|
Register Ansible variable property
|
Using Ansible I'm having a problem registering a variable the way I want. Using the implementation below I will always have to call .stdout on the variable - is there a way I can do better? My playbook: Note the unwanted use of .stdout - I just want to be able to use the variable directly without calling a propery...? --- - name: prepare for new deployment hosts: all user: ser85 tasks: - name: init deploy dir shell: echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N) # [URL] register: deploy_dir - debug: var=deploy_dir - debug: var=deploy_dir.stdout - name: init scripts dir shell: echo {{ deploy_dir.stdout }}/scripts register: scripts_dir - debug: var=scripts_dir.stdout The output when I execute the playbook: TASK [init deploy dir] ********************************************************* changed: [123.123.123.123] TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "deploy_dir": { "changed": true, "cmd": "echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N)", "delta": "0:00:00.002898", "end": "2016-05-27 10:53:38.122217", "rc": 0, "start": "2016-05-27 10:53:38.119319", "stderr": "", "stdout": "ansible-deploy-20160527-105338-121888719", "stdout_lines": [ "ansible-deploy-20160527-105338-121888719" ], "warnings": [] } } TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "deploy_dir.stdout": "ansible-deploy-20160527-105338-121888719" } TASK [init scripts dir] ******************************************************** changed: [123.123.123.123] TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "scripts_dir.stdout": "ansible-deploy-20160527-105338-121888719/scripts" } Any help or insights appreciated - thank you :)
|
Register Ansible variable property Using Ansible I'm having a problem registering a variable the way I want. Using the implementation below I will always have to call .stdout on the variable - is there a way I can do better? My playbook: Note the unwanted use of .stdout - I just want to be able to use the variable directly without calling a propery...? --- - name: prepare for new deployment hosts: all user: ser85 tasks: - name: init deploy dir shell: echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N) # [URL] register: deploy_dir - debug: var=deploy_dir - debug: var=deploy_dir.stdout - name: init scripts dir shell: echo {{ deploy_dir.stdout }}/scripts register: scripts_dir - debug: var=scripts_dir.stdout The output when I execute the playbook: TASK [init deploy dir] ********************************************************* changed: [123.123.123.123] TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "deploy_dir": { "changed": true, "cmd": "echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N)", "delta": "0:00:00.002898", "end": "2016-05-27 10:53:38.122217", "rc": 0, "start": "2016-05-27 10:53:38.119319", "stderr": "", "stdout": "ansible-deploy-20160527-105338-121888719", "stdout_lines": [ "ansible-deploy-20160527-105338-121888719" ], "warnings": [] } } TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "deploy_dir.stdout": "ansible-deploy-20160527-105338-121888719" } TASK [init scripts dir] ******************************************************** changed: [123.123.123.123] TASK [debug] ******************************************************************* ok: [123.123.123.123] => { "scripts_dir.stdout": "ansible-deploy-20160527-105338-121888719/scripts" } Any help or insights appreciated - thank you :)
|
ansible
| 21
| 40,949
| 1
|
https://stackoverflow.com/questions/37479605/register-ansible-variable-property
|
28,885,184
|
default value for dictionary in jinja2 (ansible)
|
jinja2 has filter '|default()' to works with undefined variables. But it does not work with dictionary values. if D may have or not have key foo (D[foo]), than: {{ D[foo]|default ('no foo') }} will prints 'no foo' if D is undefined, but will cause error ('dict object' has no attribute 'foo') if D is defined, but D[foo] is undefined. Is any way to make default for dictionary item?
|
default value for dictionary in jinja2 (ansible) jinja2 has filter '|default()' to works with undefined variables. But it does not work with dictionary values. if D may have or not have key foo (D[foo]), than: {{ D[foo]|default ('no foo') }} will prints 'no foo' if D is undefined, but will cause error ('dict object' has no attribute 'foo') if D is defined, but D[foo] is undefined. Is any way to make default for dictionary item?
|
jinja2, ansible
| 21
| 31,684
| 1
|
https://stackoverflow.com/questions/28885184/default-value-for-dictionary-in-jinja2-ansible
|
46,720,411
|
Is it safe to edit /etc/sudoers with the Ansible "lineinfile" module?
|
I want to change sudo session timeout according to this answer. I can edit ordinary file: lineinfile: path: /etc/sudoers regexp: ^Defaults env_reset line: Defaults env_reset,timestamp_timeout=60 But in first line of my /etc/sudoers written: # This file MUST be edited with the 'visudo' command as root. How to deal with it? P.S. Despite the fact that the short answer is yes, one must read Konstantin Suvorov answer about right way to do it with lineinfile and very interesting techraf answer about possible pitfalls on this way
|
Is it safe to edit /etc/sudoers with the Ansible "lineinfile" module? I want to change sudo session timeout according to this answer. I can edit ordinary file: lineinfile: path: /etc/sudoers regexp: ^Defaults env_reset line: Defaults env_reset,timestamp_timeout=60 But in first line of my /etc/sudoers written: # This file MUST be edited with the 'visudo' command as root. How to deal with it? P.S. Despite the fact that the short answer is yes, one must read Konstantin Suvorov answer about right way to do it with lineinfile and very interesting techraf answer about possible pitfalls on this way
|
ansible
| 20
| 23,822
| 5
|
https://stackoverflow.com/questions/46720411/is-it-safe-to-edit-etc-sudoers-with-the-ansible-lineinfile-module
|
57,571,765
|
Restart service when service file changes when using Ansible
|
I am creating a systemd service using template module --- - name: Systemd service template: src: sonar.unit.j2 dest: /etc/systemd/system/sonarqube.service when: "ansible_service_mgr == 'systemd'" The contents of the sonarqube.service can change of course. On change I want to restart the service. How can I do this?
|
Restart service when service file changes when using Ansible I am creating a systemd service using template module --- - name: Systemd service template: src: sonar.unit.j2 dest: /etc/systemd/system/sonarqube.service when: "ansible_service_mgr == 'systemd'" The contents of the sonarqube.service can change of course. On change I want to restart the service. How can I do this?
|
ansible, ansible-template
| 20
| 50,315
| 3
|
https://stackoverflow.com/questions/57571765/restart-service-when-service-file-changes-when-using-ansible
|
41,725,555
|
How to use omit with Ansible and avoid any errors?
|
I tried to use omit with an expression like this: id: "{{ openstack_networks.id | default(omit) }}" But it seems that it keeps failing with an exception when openstack_networks variable is not defined. What is the correct way to write this jinja2 filter? I want to omit the parameter in case openstack_networks.id does not exists.
|
How to use omit with Ansible and avoid any errors? I tried to use omit with an expression like this: id: "{{ openstack_networks.id | default(omit) }}" But it seems that it keeps failing with an exception when openstack_networks variable is not defined. What is the correct way to write this jinja2 filter? I want to omit the parameter in case openstack_networks.id does not exists.
|
ansible, jinja2, ansible-2.x
| 20
| 40,160
| 2
|
https://stackoverflow.com/questions/41725555/how-to-use-omit-with-ansible-and-avoid-any-errors
|
31,640,637
|
Ansible: how to clone a repository as other user
|
I'm trying to write deployments rules with Ansible. Some of the steps are: Update and Upgrade Server Create a user called harry Add Public and Private keys to harry Clone a Git Repository from bitbucket.org I want to clone the repository as harry user in his home directory (that's why I'm copying it's public and private keys). The issue is that it is not possible to specifiy a user the git clone must be executed as. So Ansible try to clone the repository as root and failed because he doesn't have rights to access the repository. How do you solve this ?
|
Ansible: how to clone a repository as other user I'm trying to write deployments rules with Ansible. Some of the steps are: Update and Upgrade Server Create a user called harry Add Public and Private keys to harry Clone a Git Repository from bitbucket.org I want to clone the repository as harry user in his home directory (that's why I'm copying it's public and private keys). The issue is that it is not possible to specifiy a user the git clone must be executed as. So Ansible try to clone the repository as root and failed because he doesn't have rights to access the repository. How do you solve this ?
|
git, ansible
| 20
| 39,414
| 5
|
https://stackoverflow.com/questions/31640637/ansible-how-to-clone-a-repository-as-other-user
|
41,567,196
|
Ansible: How to add variables to "command" or "shell"
|
Is it possible to use variables on command or shell modules? I have the following code, and I would like to use variable file to provide some configurations: I would like to read the Hadoop version from my variables file. On other modules of ansible I could use {{ansible_version}} , but with command or shell it doesn't works. - name: start ZooKeeper HA command: hadoop-2.7.1/bin/hdfs zkfc -formatZK -nonInteractive - name: start zkfc shell: hadoop-2.7.1/sbin/hadoop-daemon.sh start zkfc I would like to convert to the following: - name: Iniciar zkfc command: {{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc Because if I run the with this syntax it throws this error: - name: inicializar estado ZooKeeper HA command: {{hadoop_version}}/bin/hdfs zkfc -formatZK -nonInteractive ^ here We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" I have try using, but same problem: - name: Iniciar zkfc command: "{{ hadoop_version }}"/sbin/hadoop-daemon.sh start zkfc What is the correct syntax?
|
Ansible: How to add variables to "command" or "shell" Is it possible to use variables on command or shell modules? I have the following code, and I would like to use variable file to provide some configurations: I would like to read the Hadoop version from my variables file. On other modules of ansible I could use {{ansible_version}} , but with command or shell it doesn't works. - name: start ZooKeeper HA command: hadoop-2.7.1/bin/hdfs zkfc -formatZK -nonInteractive - name: start zkfc shell: hadoop-2.7.1/sbin/hadoop-daemon.sh start zkfc I would like to convert to the following: - name: Iniciar zkfc command: {{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc Because if I run the with this syntax it throws this error: - name: inicializar estado ZooKeeper HA command: {{hadoop_version}}/bin/hdfs zkfc -formatZK -nonInteractive ^ here We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" I have try using, but same problem: - name: Iniciar zkfc command: "{{ hadoop_version }}"/sbin/hadoop-daemon.sh start zkfc What is the correct syntax?
|
ansible, ansible-2.x
| 20
| 76,126
| 3
|
https://stackoverflow.com/questions/41567196/ansible-how-to-add-variables-to-command-or-shell
|
25,144,608
|
running an ansible local task in a remote playbook
|
I'm trying to get this task to run locally (on the machine that is running the playbook) : - name: get the local repo's branch name local_action: git branch | awk '/^\*/{print $2}' register: branchName I tried plenty of variations with no success all other tasks are meant to run on the target host, which is why running the whole playbook local is not an option TASK: [get the local repo's branch name] ************************************** <127.0.0.1> REMOTE_MODULE git branch | awk '/^\*/{print $2}' <127.0.0.1> EXEC ['/bin/sh', '-c', 'mkdir -p $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172 && echo $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172'] <127.0.0.1> PUT /tmp/tmpQVocvw TO /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/git <127.0.0.1> EXEC ['/bin/sh', '-c', '/usr/bin/python /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/git; rm -rf /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/ >/dev/null 2>&1'] failed: [portal-dev] => {"failed": true} msg: this module requires key=value arguments (['branch', '|', 'awk', '/^\\*/{print $2}']) FATAL: all hosts have already failed -- aborting update: I have followed bkan's suggestion (bellow), and got a bit further, but - name: get the local repo's branch name local_action: command git branch | (awk '/^\*/{print $2}') sudo: no register: branchName now the git command gets launched but not correctly (see error below). note that this command runs perfectly as a "shell" but unfortunately there is no local_shell equivalent of local_action ... failed: [portal-dev] => {"changed": true, "cmd": ["git", "branch", "|", "(awk", "/^\\*/{print $2})"], "delta": "0:00:00.002980", "end": "2014-08-05 18:00:01.293632", "rc": 129, "start": "2014-08-05 18:00:01.290652"} stderr: usage: git branch [options] [-r | -a] [--merged | --no-merged] or: git branch [options] [-l] [-f] <branchname> [<start-point>] or: git branch [options] [-r] (-d | -D) <branchname>... or: git branch [options] (-m | -M) [<oldbranch>] <newbranch> ...
|
running an ansible local task in a remote playbook I'm trying to get this task to run locally (on the machine that is running the playbook) : - name: get the local repo's branch name local_action: git branch | awk '/^\*/{print $2}' register: branchName I tried plenty of variations with no success all other tasks are meant to run on the target host, which is why running the whole playbook local is not an option TASK: [get the local repo's branch name] ************************************** <127.0.0.1> REMOTE_MODULE git branch | awk '/^\*/{print $2}' <127.0.0.1> EXEC ['/bin/sh', '-c', 'mkdir -p $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172 && echo $HOME/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172'] <127.0.0.1> PUT /tmp/tmpQVocvw TO /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/git <127.0.0.1> EXEC ['/bin/sh', '-c', '/usr/bin/python /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/git; rm -rf /home/max/.ansible/tmp/ansible-tmp-1407258765.57-75899426008172/ >/dev/null 2>&1'] failed: [portal-dev] => {"failed": true} msg: this module requires key=value arguments (['branch', '|', 'awk', '/^\\*/{print $2}']) FATAL: all hosts have already failed -- aborting update: I have followed bkan's suggestion (bellow), and got a bit further, but - name: get the local repo's branch name local_action: command git branch | (awk '/^\*/{print $2}') sudo: no register: branchName now the git command gets launched but not correctly (see error below). note that this command runs perfectly as a "shell" but unfortunately there is no local_shell equivalent of local_action ... failed: [portal-dev] => {"changed": true, "cmd": ["git", "branch", "|", "(awk", "/^\\*/{print $2})"], "delta": "0:00:00.002980", "end": "2014-08-05 18:00:01.293632", "rc": 129, "start": "2014-08-05 18:00:01.290652"} stderr: usage: git branch [options] [-r | -a] [--merged | --no-merged] or: git branch [options] [-l] [-f] <branchname> [<start-point>] or: git branch [options] [-r] (-d | -D) <branchname>... or: git branch [options] (-m | -M) [<oldbranch>] <newbranch> ...
|
ansible
| 20
| 42,520
| 1
|
https://stackoverflow.com/questions/25144608/running-an-ansible-local-task-in-a-remote-playbook
|
46,209,556
|
How can I use Ansible nested variable?
|
I have an Ansible playbook like the one below, I want use nested variable like this: msg={{{{Component}}.community_release_num}} , but when I run playbook: ansible-playbook vartest.yml -e 'version=version_402', it not work [es@vpn-server nested-var]$ tree . βββ vars β βββ horizon.yml β βββ version_402.yml βββ vartest.yml 1 directory, 3 files [es@vpn-server nested-var]$ cat vartest.yml --- - name: test hosts: localhost vars_files: - vars/{{version}}.yml tasks: - debug: msg={{{{Component}}.community_release_num}} - debug: msg={{{{Component}}.release_num}} [es@vpn-server nested-var]$ cat vars/horizon.yml Component: horizon [es@vpn-server nested-var]$ cat vars/version_402.yml - horizon: community_release_num: '9.0.1' release_num: '4.0.2' [es@vpn-server nested-var]$ error messages [es@vpn-server nested-var]$ ansible-playbook vartest.yml -e 'version=version_402' /usr/lib64/python2.6/site-packages/cryptography/__init__.py:25: DeprecationWarning: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. DeprecationWarning PLAY [test] ******************************************************************************************************* /usr/lib64/python2.6/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability. _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning) TASK [debug] ****************************************************************************************************** fatal: [localhost]: FAILED! => {"failed": true, "msg": "template error while templating string: expected token 'colon', got '}'. String: {{{{Component}}.community_release_num}}"} to retry, use: --limit @/data/wangqian/artemis-code-test/artemis/ansible/update/nested-var/vartest.retry PLAY RECAP ******************************************************************************************************** localhost : ok=0 changed=0 unreachable=0 failed=1 Can Ansible use nested variable, if yes, how to use it?
|
How can I use Ansible nested variable? I have an Ansible playbook like the one below, I want use nested variable like this: msg={{{{Component}}.community_release_num}} , but when I run playbook: ansible-playbook vartest.yml -e 'version=version_402', it not work [es@vpn-server nested-var]$ tree . βββ vars β βββ horizon.yml β βββ version_402.yml βββ vartest.yml 1 directory, 3 files [es@vpn-server nested-var]$ cat vartest.yml --- - name: test hosts: localhost vars_files: - vars/{{version}}.yml tasks: - debug: msg={{{{Component}}.community_release_num}} - debug: msg={{{{Component}}.release_num}} [es@vpn-server nested-var]$ cat vars/horizon.yml Component: horizon [es@vpn-server nested-var]$ cat vars/version_402.yml - horizon: community_release_num: '9.0.1' release_num: '4.0.2' [es@vpn-server nested-var]$ error messages [es@vpn-server nested-var]$ ansible-playbook vartest.yml -e 'version=version_402' /usr/lib64/python2.6/site-packages/cryptography/__init__.py:25: DeprecationWarning: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. DeprecationWarning PLAY [test] ******************************************************************************************************* /usr/lib64/python2.6/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability. _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning) TASK [debug] ****************************************************************************************************** fatal: [localhost]: FAILED! => {"failed": true, "msg": "template error while templating string: expected token 'colon', got '}'. String: {{{{Component}}.community_release_num}}"} to retry, use: --limit @/data/wangqian/artemis-code-test/artemis/ansible/update/nested-var/vartest.retry PLAY RECAP ******************************************************************************************************** localhost : ok=0 changed=0 unreachable=0 failed=1 Can Ansible use nested variable, if yes, how to use it?
|
ansible, jinja2
| 20
| 59,916
| 2
|
https://stackoverflow.com/questions/46209556/how-can-i-use-ansible-nested-variable
|
38,879,266
|
Is it possible to use Ansible authorized_key exclusive with multiple keys?
|
I'm fairly new in using Ansible and have been reading here and google and haven't found an answer yet. My scenario is that I have 1 user on a server but 2-3 different pub keys that need to put in it's authorized_keys file. I can successfully remove all keys, or add all keys with this script: --- - hosts: all tasks: - name: update SSH keys authorized_key: user: <user> key: "{{ lookup('file', item) }}" state: present #exclusive: yes with_fileglob: - ../files/pub_keys/*.pub With the present flag it reads and adds all the keys. With the absent flag it removes all keys listed. Problem is that I have an old key that is only on the server and I want to remove/overwrite it and for future deployments overwrite any unauthorized keys that might be on the server and not in my playbook. With the exclusive flag it only takes the last key and adds it. This would be fantastic if it would loop and recusively add all the keys. If there is a way to do this in Ansible I have not found it. Is there any way to loop over pub files and use the exclusive option at the same time?
|
Is it possible to use Ansible authorized_key exclusive with multiple keys? I'm fairly new in using Ansible and have been reading here and google and haven't found an answer yet. My scenario is that I have 1 user on a server but 2-3 different pub keys that need to put in it's authorized_keys file. I can successfully remove all keys, or add all keys with this script: --- - hosts: all tasks: - name: update SSH keys authorized_key: user: <user> key: "{{ lookup('file', item) }}" state: present #exclusive: yes with_fileglob: - ../files/pub_keys/*.pub With the present flag it reads and adds all the keys. With the absent flag it removes all keys listed. Problem is that I have an old key that is only on the server and I want to remove/overwrite it and for future deployments overwrite any unauthorized keys that might be on the server and not in my playbook. With the exclusive flag it only takes the last key and adds it. This would be fantastic if it would loop and recusively add all the keys. If there is a way to do this in Ansible I have not found it. Is there any way to loop over pub files and use the exclusive option at the same time?
|
ubuntu, ansible, authorized-keys
| 20
| 18,988
| 6
|
https://stackoverflow.com/questions/38879266/is-it-possible-to-use-ansible-authorized-key-exclusive-with-multiple-keys
|
25,576,871
|
Ansible best practice to copy directories
|
In my playbook I have - name: Grab h5bp/server-configs-nginx git: repo=[URL] dest=/tmp/server-configs-nginx version="3db5d61f81d7229d12b89e0355629249a49ee4ac" force=yes - name: Copy over h5bp configuration command: cp -r /tmp/server-configs-nginx/{{ item }} /etc/nginx/{{ item }} with_items: - "mime.types" - "h5bp/" Which raises the warning in ansible-lint: [ANSIBLE0006] cp used in place of copy module /Users/austinpray/Dropbox/DEV/opensauce/bedrock-ansible/roles/nginx/tasks/main.yml:0 Task/Handler: Copy over h5bp configuration So this raises the question: is there a better way to do this with ansible modules rather than a command?
|
Ansible best practice to copy directories In my playbook I have - name: Grab h5bp/server-configs-nginx git: repo=[URL] dest=/tmp/server-configs-nginx version="3db5d61f81d7229d12b89e0355629249a49ee4ac" force=yes - name: Copy over h5bp configuration command: cp -r /tmp/server-configs-nginx/{{ item }} /etc/nginx/{{ item }} with_items: - "mime.types" - "h5bp/" Which raises the warning in ansible-lint: [ANSIBLE0006] cp used in place of copy module /Users/austinpray/Dropbox/DEV/opensauce/bedrock-ansible/roles/nginx/tasks/main.yml:0 Task/Handler: Copy over h5bp configuration So this raises the question: is there a better way to do this with ansible modules rather than a command?
|
ansible
| 20
| 56,679
| 6
|
https://stackoverflow.com/questions/25576871/ansible-best-practice-to-copy-directories
|
47,047,876
|
How can I take a list of server names and append a resource URI and port to each?
|
I merged two lists from an Ansible inventory: set_fact: fact1: "{{ groups['group1'] + groups[group2']|list }} The output is: fact1: - server01 - server02 - server03 With the above results, I need to append https:// to the front, and a port number to the back of each element. Then I need to convert it to a comma delimited list for a server config. In this example I want: [URL] . I tried using a join: set_fact: fact2: "{{ fact1|join(':8000,') }}" which partly worked but it left the last server without a port. How can I achieve my goal?
|
How can I take a list of server names and append a resource URI and port to each? I merged two lists from an Ansible inventory: set_fact: fact1: "{{ groups['group1'] + groups[group2']|list }} The output is: fact1: - server01 - server02 - server03 With the above results, I need to append https:// to the front, and a port number to the back of each element. Then I need to convert it to a comma delimited list for a server config. In this example I want: [URL] . I tried using a join: set_fact: fact2: "{{ fact1|join(':8000,') }}" which partly worked but it left the last server without a port. How can I achieve my goal?
|
ansible, jinja2, ansible-template
| 20
| 12,755
| 3
|
https://stackoverflow.com/questions/47047876/how-can-i-take-a-list-of-server-names-and-append-a-resource-uri-and-port-to-each
|
32,584,112
|
ansible, spaces in command line variables
|
I am about to bump up the changelog of a lot of locally developed debian packages. I am using 'Ansible' to call 'dch' from the devscripts package. I am using Ansible because I already have the subversion paths to the packages listed in an Ansible variable. I would like to be able to enter the actual changelog message as a command line variable, but it seems that ansible cannot parse spaces in variables entered on the command line. I have tried ansible-playbook tag_changelog_on_packages.yml -e changelog_message="testing testing" ansible-playbook tag_changelog_on_packages.yml -e changelog_message='testing testing' ansible-playbook tag_changelog_on_packages.yml -e changelog_message=testing\ testing ansible-playbook tag_changelog_on_packages.yml -e changelog_message="testing\ testing" In all cases I only get the first "testing" . The last try makes ansible crash with ValueError: No escaped character probably because the whitespace is stripped. Am I missing anything ? Cheers
|
ansible, spaces in command line variables I am about to bump up the changelog of a lot of locally developed debian packages. I am using 'Ansible' to call 'dch' from the devscripts package. I am using Ansible because I already have the subversion paths to the packages listed in an Ansible variable. I would like to be able to enter the actual changelog message as a command line variable, but it seems that ansible cannot parse spaces in variables entered on the command line. I have tried ansible-playbook tag_changelog_on_packages.yml -e changelog_message="testing testing" ansible-playbook tag_changelog_on_packages.yml -e changelog_message='testing testing' ansible-playbook tag_changelog_on_packages.yml -e changelog_message=testing\ testing ansible-playbook tag_changelog_on_packages.yml -e changelog_message="testing\ testing" In all cases I only get the first "testing" . The last try makes ansible crash with ValueError: No escaped character probably because the whitespace is stripped. Am I missing anything ? Cheers
|
ansible
| 20
| 23,339
| 1
|
https://stackoverflow.com/questions/32584112/ansible-spaces-in-command-line-variables
|
54,965,199
|
Did not find expected key while parsing a block mapping
|
Am running ansible play-book but getting below error, -using ansible 2.7.6, ubuntu 16.04. in playbook am mentioned (<unknown>): did not find expected key while parsing a block mapping at line 6 column 3 I tried without become-yes,ubuntu,sudo that also getting the same issue and ansible saying: The offending line appears to be: - name: build npm ^ here - hosts: all vars: app_dir: /home/ubuntu/app/backend-app-name tasks: - name: build npm command: "chdir={{ app_dir }} {{ item }}" with_items: - /usr/bin/npm run build become: yes become_user: ubuntu become_method: sudo
|
Did not find expected key while parsing a block mapping Am running ansible play-book but getting below error, -using ansible 2.7.6, ubuntu 16.04. in playbook am mentioned (<unknown>): did not find expected key while parsing a block mapping at line 6 column 3 I tried without become-yes,ubuntu,sudo that also getting the same issue and ansible saying: The offending line appears to be: - name: build npm ^ here - hosts: all vars: app_dir: /home/ubuntu/app/backend-app-name tasks: - name: build npm command: "chdir={{ app_dir }} {{ item }}" with_items: - /usr/bin/npm run build become: yes become_user: ubuntu become_method: sudo
|
node.js, ubuntu, ansible
| 20
| 112,100
| 3
|
https://stackoverflow.com/questions/54965199/did-not-find-expected-key-while-parsing-a-block-mapping
|
39,539,559
|
Ansible - procesor_count vs processor_cores vs processor_vcpus
|
I got puzzled setting up server with the following cpu facts: "ansible_processor": [ "GenuineIntel", "Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz", "GenuineIntel", "Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz" ], "ansible_processor_cores": 1, "ansible_processor_count": 2, "ansible_processor_threads_per_core": 1, "ansible_processor_vcpus": 2, It seems to report the number of CPUs correctly but what should I base my workers (threads) number on? I was sure I'd use ansible_processor_cores but it seems to report only one (1 - sic!) despite reporting two processors! How do you get the number of threads available for worker processes?
|
Ansible - procesor_count vs processor_cores vs processor_vcpus I got puzzled setting up server with the following cpu facts: "ansible_processor": [ "GenuineIntel", "Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz", "GenuineIntel", "Intel(R) Xeon(R) CPU E5-2650L v3 @ 1.80GHz" ], "ansible_processor_cores": 1, "ansible_processor_count": 2, "ansible_processor_threads_per_core": 1, "ansible_processor_vcpus": 2, It seems to report the number of CPUs correctly but what should I base my workers (threads) number on? I was sure I'd use ansible_processor_cores but it seems to report only one (1 - sic!) despite reporting two processors! How do you get the number of threads available for worker processes?
|
multithreading, ansible
| 20
| 28,926
| 1
|
https://stackoverflow.com/questions/39539559/ansible-procesor-count-vs-processor-cores-vs-processor-vcpus
|
39,072,079
|
How can I dynamically change an Ansible variable?
|
I have this in vars: var1: "test1" var2: "test2" var3: "{{var1}}" Now I want to dynamically change var3: "{{var2}}" . I can assign var3: "test2" . But how can I assign var3: "{{var2}}" ?
|
How can I dynamically change an Ansible variable? I have this in vars: var1: "test1" var2: "test2" var3: "{{var1}}" Now I want to dynamically change var3: "{{var2}}" . I can assign var3: "test2" . But how can I assign var3: "{{var2}}" ?
|
ansible
| 20
| 46,898
| 1
|
https://stackoverflow.com/questions/39072079/how-can-i-dynamically-change-an-ansible-variable
|
25,346,796
|
How can I change the path of group_vars and host_vars?
|
we can change the path of roles by modifying roles_path in ansible.cfg . But the document doesn't seems to mention anything about changing the path of group_vars and host_vars . How can I change those paths? I will integrate the files related to ansible with rails app repsitory. I want to gather the roles and vars directory under single directory but leave hosts file and ansible.cfg at the top directory so that the top directory is easy to see and still I can run ansible-playbook at the top directory without moving to deep directory. Thanks, in advance.
|
How can I change the path of group_vars and host_vars? we can change the path of roles by modifying roles_path in ansible.cfg . But the document doesn't seems to mention anything about changing the path of group_vars and host_vars . How can I change those paths? I will integrate the files related to ansible with rails app repsitory. I want to gather the roles and vars directory under single directory but leave hosts file and ansible.cfg at the top directory so that the top directory is easy to see and still I can run ansible-playbook at the top directory without moving to deep directory. Thanks, in advance.
|
ansible
| 20
| 28,679
| 2
|
https://stackoverflow.com/questions/25346796/how-can-i-change-the-path-of-group-vars-and-host-vars
|
32,661,912
|
Playbooks in a subdirectory, not next to group_vars
|
Does anyone know how to put playbooks into folders, but share the same roles, group_vars, and other stuff typically located at the root dir? Here's what I'd like to have: root_dir: - group_vars - roles - inventory - playbooks - my_playbook.yml - site.yml - deploy.yml Our root dir is getting pretty big now and I'd like to split out some playbooks into their own folder (shown as playbooks/ above). An identical tiny playbook fails to run when inside a directory (say, playbooks/) vs at the root dir, because it doesn't grab stuff from group_vars. I can partially work around this, and run a playbook inside my playbooks/ directory: - hosts: host_group sudo: true gather_facts: false vars_files: - ../group_vars/all/main.yml This picks up the vars defined in main.yml. However, it's not clear to me if this would add group variables defined in group_vars/, as opposed to the explicitly specificed ../group_vars/. Thanks!
|
Playbooks in a subdirectory, not next to group_vars Does anyone know how to put playbooks into folders, but share the same roles, group_vars, and other stuff typically located at the root dir? Here's what I'd like to have: root_dir: - group_vars - roles - inventory - playbooks - my_playbook.yml - site.yml - deploy.yml Our root dir is getting pretty big now and I'd like to split out some playbooks into their own folder (shown as playbooks/ above). An identical tiny playbook fails to run when inside a directory (say, playbooks/) vs at the root dir, because it doesn't grab stuff from group_vars. I can partially work around this, and run a playbook inside my playbooks/ directory: - hosts: host_group sudo: true gather_facts: false vars_files: - ../group_vars/all/main.yml This picks up the vars defined in main.yml. However, it's not clear to me if this would add group variables defined in group_vars/, as opposed to the explicitly specificed ../group_vars/. Thanks!
|
ansible
| 20
| 17,752
| 5
|
https://stackoverflow.com/questions/32661912/playbooks-in-a-subdirectory-not-next-to-group-vars
|
36,630,299
|
How do I avoid ansible deployment failures due to dpkg lock file?
|
It seems that getting failures due to /var/lib/dpkg/lock is something not very rare. Based on observations these are caused most of the time 9/10 due to state lock file or while a cron job was running. This means that a retry mechanism combined with a removal of stale file could be the solution. How can I do this in ansible?
|
How do I avoid ansible deployment failures due to dpkg lock file? It seems that getting failures due to /var/lib/dpkg/lock is something not very rare. Based on observations these are caused most of the time 9/10 due to state lock file or while a cron job was running. This means that a retry mechanism combined with a removal of stale file could be the solution. How can I do this in ansible?
|
ansible
| 20
| 9,596
| 3
|
https://stackoverflow.com/questions/36630299/how-do-i-avoid-ansible-deployment-failures-due-to-dpkg-lock-file
|
35,176,548
|
Authentication or permission failure, did not have permissions on the remote directory
|
I am using ansijet to automate the ansible playbook to be run on a button click. The playbook is to stop the running instances on AWS. If run, manually from command-line, the playbook runs well and do the tasks. But when run through the web interface of ansijet , following error is encountered Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in "/tmp". Failed command was: mkdir -p $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742 && echo $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742, exited with result 1: Following is the ansible.cfg configuration. # some basic default values... inventory = /etc/ansible/hosts #library = /usr/share/my_modules/ remote_tmp = $HOME/.ansible/tmp/ pattern = * forks = 5 poll_interval = 15 sudo_user = root #ask_sudo_pass = True #ask_pass = True transport = smart #remote_port = 22 module_lang = C I try to change the remote_tmp path to /home/ubuntu/.ansible/tmp But still getting the same error.
|
Authentication or permission failure, did not have permissions on the remote directory I am using ansijet to automate the ansible playbook to be run on a button click. The playbook is to stop the running instances on AWS. If run, manually from command-line, the playbook runs well and do the tasks. But when run through the web interface of ansijet , following error is encountered Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in "/tmp". Failed command was: mkdir -p $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742 && chmod a+rx $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742 && echo $HOME/.ansible/tmp/ansible-tmp-1390414200.76-192986604554742, exited with result 1: Following is the ansible.cfg configuration. # some basic default values... inventory = /etc/ansible/hosts #library = /usr/share/my_modules/ remote_tmp = $HOME/.ansible/tmp/ pattern = * forks = 5 poll_interval = 15 sudo_user = root #ask_sudo_pass = True #ask_pass = True transport = smart #remote_port = 22 module_lang = C I try to change the remote_tmp path to /home/ubuntu/.ansible/tmp But still getting the same error.
|
amazon-web-services, ansible
| 20
| 72,816
| 8
|
https://stackoverflow.com/questions/35176548/authentication-or-permission-failure-did-not-have-permissions-on-the-remote-dir
|
74,701,206
|
Install Ansible Windows Machine
|
I have tried installing ansible through pip install ansible but whenever i get the following error trying to use it: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Scripts\ansible.exe\__main__.py", line 4, in <module> File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Lib\site-packages\ansible\cli\__init__.py", line 42, in <module> check_blocking_io() File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Lib\site-packages\ansible\cli\__init__.py", line 34, in check_blocking_io if not os.get_blocking(fd): ^^^^^^^^^^^^^^^ AttributeError: module 'os' has no attribute 'get_blocking' I have python and pip installed on the machine.
|
Install Ansible Windows Machine I have tried installing ansible through pip install ansible but whenever i get the following error trying to use it: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Scripts\ansible.exe\__main__.py", line 4, in <module> File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Lib\site-packages\ansible\cli\__init__.py", line 42, in <module> check_blocking_io() File "C:\Users\ruan.greyling\AppData\Local\Programs\Python\Python311\Lib\site-packages\ansible\cli\__init__.py", line 34, in check_blocking_io if not os.get_blocking(fd): ^^^^^^^^^^^^^^^ AttributeError: module 'os' has no attribute 'get_blocking' I have python and pip installed on the machine.
|
python, ansible
| 20
| 26,864
| 3
|
https://stackoverflow.com/questions/74701206/install-ansible-windows-machine
|
25,698,059
|
how to run multiple ansible plays in parallel?
|
I have a playbook with multiple plays: --- - hosts: druid-realtime-1 sudo: true roles: - { role: druid-realtime, du_rt_id: 1 } - hosts: druid-realtime-2 sudo: true roles: - { role: druid-realtime, du_rt_id: 2 } How do I tell ansible to run both plays in parallel instead of one after another?
|
how to run multiple ansible plays in parallel? I have a playbook with multiple plays: --- - hosts: druid-realtime-1 sudo: true roles: - { role: druid-realtime, du_rt_id: 1 } - hosts: druid-realtime-2 sudo: true roles: - { role: druid-realtime, du_rt_id: 2 } How do I tell ansible to run both plays in parallel instead of one after another?
|
ansible
| 20
| 20,044
| 5
|
https://stackoverflow.com/questions/25698059/how-to-run-multiple-ansible-plays-in-parallel
|
38,522,538
|
How to make ansible only ask for become password when required
|
I am using ansible 2.0.2.0 to update my static website from any computer. My playbook runs on localhost only and essentially has two parts: Privileged part: Ensure packages are installed, essentially apt tasks with become: true Unprivileged part: Fill in templates, minify and sync with web hosting service, essentially command tasks without become . I would prefer having these two parts in the same playbook so that I do not need to worry about dependencies when switching computers. Ideally, I would like ansible to check if the apt packages are installed and only ask for the become password if it needs to install any. Other, less satisfactory alternatives that I have explored so far and their drawbacks are highlighted below: sudo ansible-playbook ... : Runs the unprivileged part as root , asks sudo password when not required; ansible-playbook --ask-become-pass ... : Always asks sudo password, even if no new packages need to be installed; ansible-playbook ... : Fails with sudo: a password is required . Is there any way to keep the privileged and unprivileged parts in the same playbook without needlessly typing the sudo password nor giving needless privileges to the unprivileged part?
|
How to make ansible only ask for become password when required I am using ansible 2.0.2.0 to update my static website from any computer. My playbook runs on localhost only and essentially has two parts: Privileged part: Ensure packages are installed, essentially apt tasks with become: true Unprivileged part: Fill in templates, minify and sync with web hosting service, essentially command tasks without become . I would prefer having these two parts in the same playbook so that I do not need to worry about dependencies when switching computers. Ideally, I would like ansible to check if the apt packages are installed and only ask for the become password if it needs to install any. Other, less satisfactory alternatives that I have explored so far and their drawbacks are highlighted below: sudo ansible-playbook ... : Runs the unprivileged part as root , asks sudo password when not required; ansible-playbook --ask-become-pass ... : Always asks sudo password, even if no new packages need to be installed; ansible-playbook ... : Fails with sudo: a password is required . Is there any way to keep the privileged and unprivileged parts in the same playbook without needlessly typing the sudo password nor giving needless privileges to the unprivileged part?
|
ansible
| 20
| 14,955
| 1
|
https://stackoverflow.com/questions/38522538/how-to-make-ansible-only-ask-for-become-password-when-required
|
26,475,761
|
ansible: pass variable to a handler
|
I use an "eye" as a supervisor and on changes in templates have to runs something like this: eye load service.rb eye restart service.rb I want to define this as a single handler for all the apps and call it like eye reload appname And in a handler operate like this: - name: reload eye service command: eye load /path/{{ service }}.rb && eye restart {{ service }} But I can't find a way to pass variable to a handler. Is it possible?
|
ansible: pass variable to a handler I use an "eye" as a supervisor and on changes in templates have to runs something like this: eye load service.rb eye restart service.rb I want to define this as a single handler for all the apps and call it like eye reload appname And in a handler operate like this: - name: reload eye service command: eye load /path/{{ service }}.rb && eye restart {{ service }} But I can't find a way to pass variable to a handler. Is it possible?
|
ansible
| 20
| 24,889
| 4
|
https://stackoverflow.com/questions/26475761/ansible-pass-variable-to-a-handler
|
41,971,169
|
Getting the newest filename in a directory in Ansible
|
I have an Ansible script, and I am trying to get the filename of the newest item in a directory. I am using this Ansible script: - name: Finding newest file in a folder find: paths: "/var/www/html/wwwroot/somefolder/" age: "latest" age_stamp: mtime However, I am getting the following error - FAILED! => {"age": "latest", "changed": false, "failed": true, "msg": "failed to process age"} How can I get Ansible to retrieve the filename of the newest file in a directory?
|
Getting the newest filename in a directory in Ansible I have an Ansible script, and I am trying to get the filename of the newest item in a directory. I am using this Ansible script: - name: Finding newest file in a folder find: paths: "/var/www/html/wwwroot/somefolder/" age: "latest" age_stamp: mtime However, I am getting the following error - FAILED! => {"age": "latest", "changed": false, "failed": true, "msg": "failed to process age"} How can I get Ansible to retrieve the filename of the newest file in a directory?
|
ansible
| 19
| 19,653
| 2
|
https://stackoverflow.com/questions/41971169/getting-the-newest-filename-in-a-directory-in-ansible
|
41,875,645
|
Evaluate dynamic variable name in ansible
|
I have vars where I put something like this: vars/main.yml hello_port: 80 world_port: 81 in my ansbile file I load the vars with vars_files: - ./vars/main.yml This is how I initialize m_name: - name: set_fact set_fact: m_name: - 'hello' - 'world' and after that I have task with iterate using with_items: - debug: msg: "{{ (item + '_port') }}" with_items: "{{ m_name }}" But I've got as output hello_port world_port not their values. OK I find that if I use debug var it is working. But If I want to put this expression "{{ (item + '_port') }}" for an example in shell task it does not evaluate it. Is there a way to evaluate the dynamically created variables name - to get the value?
|
Evaluate dynamic variable name in ansible I have vars where I put something like this: vars/main.yml hello_port: 80 world_port: 81 in my ansbile file I load the vars with vars_files: - ./vars/main.yml This is how I initialize m_name: - name: set_fact set_fact: m_name: - 'hello' - 'world' and after that I have task with iterate using with_items: - debug: msg: "{{ (item + '_port') }}" with_items: "{{ m_name }}" But I've got as output hello_port world_port not their values. OK I find that if I use debug var it is working. But If I want to put this expression "{{ (item + '_port') }}" for an example in shell task it does not evaluate it. Is there a way to evaluate the dynamically created variables name - to get the value?
|
ansible, dynamic-variables
| 19
| 55,596
| 4
|
https://stackoverflow.com/questions/41875645/evaluate-dynamic-variable-name-in-ansible
|
22,398,302
|
Ansible: Is it possible to search replace single word
|
In the lineinfile module, it replaces the full line. If the line is long I have to repeat the whole line again. Let us suppose I want to replace the single word in the file: #abc.conf This is my horse this is the playbook: - lineinfile: dest=abc.conf state=present regexp='horse' line='This is my dog' backup=yes is there any way to achieve someting like sed 's/horse/dog/g' ?
|
Ansible: Is it possible to search replace single word In the lineinfile module, it replaces the full line. If the line is long I have to repeat the whole line again. Let us suppose I want to replace the single word in the file: #abc.conf This is my horse this is the playbook: - lineinfile: dest=abc.conf state=present regexp='horse' line='This is my dog' backup=yes is there any way to achieve someting like sed 's/horse/dog/g' ?
|
linux, ansible
| 19
| 37,265
| 3
|
https://stackoverflow.com/questions/22398302/ansible-is-it-possible-to-search-replace-single-word
|
39,805,949
|
how to use include_vars in ansible
|
I have created my own custom library, I added my custom library in the common folder of my repository. In that I need to pass variables dynamically. It's a confidential password, so I am using "vault" in ansible. In that my requirement is how to pass include_vars in the tasks\main.yml before hosts. e.g: mytasks.yml - include_vars: sample_vault.yml - include: sample_tasks.yml - hosts: localhost tasks: name: "free task" command: ls -a my directory structure like this: myfolder - common -library -my file.py - sample_tasks.yml - mytasks -mytasks.yml(my main master playbook file) -sample_vault.yml (note:i create this using vault for confidential purpose) - roles -myrole Here I need to run sample_tasks file using a variables passed in sample_vault.yml file before I execute the hosts tasks using ansible. If I use extra variable means password is visible so I don't need that. When I use include_vars in my tasks/main.yml file, it shows the following error: ERROR! 'include_vars' is not a valid attribute for a Play
|
how to use include_vars in ansible I have created my own custom library, I added my custom library in the common folder of my repository. In that I need to pass variables dynamically. It's a confidential password, so I am using "vault" in ansible. In that my requirement is how to pass include_vars in the tasks\main.yml before hosts. e.g: mytasks.yml - include_vars: sample_vault.yml - include: sample_tasks.yml - hosts: localhost tasks: name: "free task" command: ls -a my directory structure like this: myfolder - common -library -my file.py - sample_tasks.yml - mytasks -mytasks.yml(my main master playbook file) -sample_vault.yml (note:i create this using vault for confidential purpose) - roles -myrole Here I need to run sample_tasks file using a variables passed in sample_vault.yml file before I execute the hosts tasks using ansible. If I use extra variable means password is visible so I don't need that. When I use include_vars in my tasks/main.yml file, it shows the following error: ERROR! 'include_vars' is not a valid attribute for a Play
|
include, ansible, ansible-vault
| 19
| 52,856
| 1
|
https://stackoverflow.com/questions/39805949/how-to-use-include-vars-in-ansible
|
35,970,686
|
Ansible: SSH Error: unix_listener: too long for Unix domain socket
|
This is a known issue and I found a solution but it's not working for me. First I had: fatal: [openshift-node-compute-e50xx] => SSH Error: ControlPath too long It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. So I created a ~/.ansible.cfg . The content of it: [ssh_connection] control_path=%(directory)s/%%hβ%%r But after rerunning my ansible I stil have an error about 'too long'. fatal: [openshift-master-32axx] => SSH Error: unix_listener: "/Users/myuser/.ansible/cp/ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com-centos.AAZFTHkT5xXXXXXX" too long for Unix domain socket while connecting to 52.xx.xx.xx:22 It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. Why is it still too long?
|
Ansible: SSH Error: unix_listener: too long for Unix domain socket This is a known issue and I found a solution but it's not working for me. First I had: fatal: [openshift-node-compute-e50xx] => SSH Error: ControlPath too long It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. So I created a ~/.ansible.cfg . The content of it: [ssh_connection] control_path=%(directory)s/%%hβ%%r But after rerunning my ansible I stil have an error about 'too long'. fatal: [openshift-master-32axx] => SSH Error: unix_listener: "/Users/myuser/.ansible/cp/ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com-centos.AAZFTHkT5xXXXXXX" too long for Unix domain socket while connecting to 52.xx.xx.xx:22 It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue. Why is it still too long?
|
ssh, amazon-ec2, ansible
| 19
| 18,227
| 4
|
https://stackoverflow.com/questions/35970686/ansible-ssh-error-unix-listener-too-long-for-unix-domain-socket
|
30,139,810
|
How to run a shell command in ansible's check mode?
|
In check mode, I want to display the current commit in the server. I'm using the shell command ( git rev-parse HEAD ) to register the variable and then print/debug it but ansible skips shell commands in check mode. Is there anyway to mark a shell command as safe to run in check mode? Or any ansible module to do what I want? I checked into git's module but it only looks like it does checkouts. Any input would be appreciated.
|
How to run a shell command in ansible's check mode? In check mode, I want to display the current commit in the server. I'm using the shell command ( git rev-parse HEAD ) to register the variable and then print/debug it but ansible skips shell commands in check mode. Is there anyway to mark a shell command as safe to run in check mode? Or any ansible module to do what I want? I checked into git's module but it only looks like it does checkouts. Any input would be appreciated.
|
git, shell, ansible
| 19
| 18,586
| 3
|
https://stackoverflow.com/questions/30139810/how-to-run-a-shell-command-in-ansibles-check-mode
|
54,904,433
|
How to add multiple inventory files in command line while executing a playbook
|
I am having a playbook with two different plays Sample.yml - name : Play1 hosts: Host1 tasks: ... - name: Play2 hosts: Host2 tasks: ... I need to run this playbook with two different hosts( Host1 and Host2 ) and these two different hosts are present in two separate files( Hostfile1 and Hostfile2 ) under inventory/ directory. inventory/ Hostfile1 Hostfile2 . . HostfileN I want to know how to include two different hosts file while running the playbook. I know by including the entire folder ( inventory/ ) in command line we can achieve this but I have lot of hosts files inside inventory/ folder so this option will load unused hosts file. I tried to run like below ansible-playbook -i inventory/Hostfile1,Hostfile2 sample.yml But this didn't work. So, do anyone know how to run the playbook by providing multiple hosts file in command line?
|
How to add multiple inventory files in command line while executing a playbook I am having a playbook with two different plays Sample.yml - name : Play1 hosts: Host1 tasks: ... - name: Play2 hosts: Host2 tasks: ... I need to run this playbook with two different hosts( Host1 and Host2 ) and these two different hosts are present in two separate files( Hostfile1 and Hostfile2 ) under inventory/ directory. inventory/ Hostfile1 Hostfile2 . . HostfileN I want to know how to include two different hosts file while running the playbook. I know by including the entire folder ( inventory/ ) in command line we can achieve this but I have lot of hosts files inside inventory/ folder so this option will load unused hosts file. I tried to run like below ansible-playbook -i inventory/Hostfile1,Hostfile2 sample.yml But this didn't work. So, do anyone know how to run the playbook by providing multiple hosts file in command line?
|
ansible, ansible-2.x, ansible-inventory
| 19
| 29,687
| 2
|
https://stackoverflow.com/questions/54904433/how-to-add-multiple-inventory-files-in-command-line-while-executing-a-playbook
|
42,506,865
|
Ansible - Play with hosts in order I desire
|
When running a playbook Ansible randomly sets a node as first, second and third. ok: [node-p02] ok: [node-p03] ok: [node-p01] Q: How can I configure Ansible to let it execute with the hosts in sorted order? Example: ok: [node-p01] ok: [node-p02] ok: [node-p03] Serial: 1 is not an option, since it slows down the play, and my playbook is meant for 3 nodes in a single play.
|
Ansible - Play with hosts in order I desire When running a playbook Ansible randomly sets a node as first, second and third. ok: [node-p02] ok: [node-p03] ok: [node-p01] Q: How can I configure Ansible to let it execute with the hosts in sorted order? Example: ok: [node-p01] ok: [node-p02] ok: [node-p03] Serial: 1 is not an option, since it slows down the play, and my playbook is meant for 3 nodes in a single play.
|
ansible
| 19
| 31,828
| 3
|
https://stackoverflow.com/questions/42506865/ansible-play-with-hosts-in-order-i-desire
|
42,942,875
|
How to make Ansible playbook run on first host in the group?
|
How can I run a playbook only on first host in the group? I am expecting something like this: --- - name: playbook that only run on first host in the group hosts: "{{ groups[group_name] | first }}" tasks: - debug: msg: "on {{ inventory_hostname }}" But this doesn't work, gives error: 'groups' is undefined How can I make it work?
|
How to make Ansible playbook run on first host in the group? How can I run a playbook only on first host in the group? I am expecting something like this: --- - name: playbook that only run on first host in the group hosts: "{{ groups[group_name] | first }}" tasks: - debug: msg: "on {{ inventory_hostname }}" But this doesn't work, gives error: 'groups' is undefined How can I make it work?
|
ansible, ansible-inventory
| 19
| 25,210
| 1
|
https://stackoverflow.com/questions/42942875/how-to-make-ansible-playbook-run-on-first-host-in-the-group
|
45,740,777
|
ansible parse text string from stdout
|
My problem is with ansible and parsing stdout. I need to capture the stdout from an ansible play and parse this output for a specific substring within stdout and save into a var. My specific use case is below - shell: "vault.sh --keystore EAP_HOME/vault/vault.keystore | --keystore-password vault22 --alias vault --vault-block | vb --attribute password --sec-attr 0penS3sam3 --enc-dir | EAP_HOME/vault/ --iteration 120 --salt 1234abcd" register: results become: true This generates an output with the following line, the goal is to capture the masked key that jboss vault generates and save that in an ansible var so I can use it to configure the standalone.xml template: vault-option name="KEYSTORE_PASSWORD" value="MASK-5dOaAVafCSd"/> I need a way parse this string with possibly regex and save the "MASK-5dOaAVafCSd" substring into an ansible var using set_facts module or any other ansible module. Currently my code looks like this #example stdout results: vault-option name=\"KEYSTORE_PASSWORD\" value=\"MASK-5dOaAVafCSd\"/> - name: JBOSS_VAULT:define keystore password masked value variable set_fact: masked_value: | "{{ results.stdout | regex_replace('^.+(MASK-.+?)\\.+','\\\1') }}" This code is defining masked_value as the results.stdout , not the expected capture group.
|
ansible parse text string from stdout My problem is with ansible and parsing stdout. I need to capture the stdout from an ansible play and parse this output for a specific substring within stdout and save into a var. My specific use case is below - shell: "vault.sh --keystore EAP_HOME/vault/vault.keystore | --keystore-password vault22 --alias vault --vault-block | vb --attribute password --sec-attr 0penS3sam3 --enc-dir | EAP_HOME/vault/ --iteration 120 --salt 1234abcd" register: results become: true This generates an output with the following line, the goal is to capture the masked key that jboss vault generates and save that in an ansible var so I can use it to configure the standalone.xml template: vault-option name="KEYSTORE_PASSWORD" value="MASK-5dOaAVafCSd"/> I need a way parse this string with possibly regex and save the "MASK-5dOaAVafCSd" substring into an ansible var using set_facts module or any other ansible module. Currently my code looks like this #example stdout results: vault-option name=\"KEYSTORE_PASSWORD\" value=\"MASK-5dOaAVafCSd\"/> - name: JBOSS_VAULT:define keystore password masked value variable set_fact: masked_value: | "{{ results.stdout | regex_replace('^.+(MASK-.+?)\\.+','\\\1') }}" This code is defining masked_value as the results.stdout , not the expected capture group.
|
regex, string, ansible, stdout
| 19
| 83,776
| 2
|
https://stackoverflow.com/questions/45740777/ansible-parse-text-string-from-stdout
|
38,078,247
|
how to create Ansible playbook to obtain OS versions of the remote hosts?
|
I'm new to ansible. I have a requirement that requires me to pull OS version for of more than 450 linux severs hosted in AWS. AWS does not provide this feature - it rather suggests us to get it from puppet or chef. I created few simple playbooks which does not run --- - hosts: testmachine user: ec2-user sudo: yes tasks: - name: Update all packages to latest yum: name=* state=latest task: - name: obtain OS version shell: Redhat-release playbook should output a text file with hostname and OS version. Any insight on this will be highly appreciated.
|
how to create Ansible playbook to obtain OS versions of the remote hosts? I'm new to ansible. I have a requirement that requires me to pull OS version for of more than 450 linux severs hosted in AWS. AWS does not provide this feature - it rather suggests us to get it from puppet or chef. I created few simple playbooks which does not run --- - hosts: testmachine user: ec2-user sudo: yes tasks: - name: Update all packages to latest yum: name=* state=latest task: - name: obtain OS version shell: Redhat-release playbook should output a text file with hostname and OS version. Any insight on this will be highly appreciated.
|
linux, amazon-web-services, amazon-ec2, ansible
| 19
| 71,628
| 6
|
https://stackoverflow.com/questions/38078247/how-to-create-ansible-playbook-to-obtain-os-versions-of-the-remote-hosts
|
29,745,534
|
How do I pretty print an object in ansible?
|
I want to pretty print a registered object in ansible to help with debugging. How do I do it?
|
How do I pretty print an object in ansible? I want to pretty print a registered object in ansible to help with debugging. How do I do it?
|
ansible
| 19
| 44,149
| 2
|
https://stackoverflow.com/questions/29745534/how-do-i-pretty-print-an-object-in-ansible
|
57,070,583
|
Using chown command in ansible?
|
I have a command in ubuntu as sudo chown $(id -u):$(id -g) $HOME/.kube/config I want to convert into ansible script. I have tried below - name: Changing ownership command: chown $(id -u):$(id -g) $HOME/.kube/config become: true but i am getting error as below fatal: [ubuntu]: FAILED! => {"changed": t> fatal: [ubuntu]: FAILED! => {"changed": true, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []}rue, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []} EDIT: File module also did not work. - name: Create a symbolic link file: path: $HOME/.kube owner: $(id -u) group: $(id -g)
|
Using chown command in ansible? I have a command in ubuntu as sudo chown $(id -u):$(id -g) $HOME/.kube/config I want to convert into ansible script. I have tried below - name: Changing ownership command: chown $(id -u):$(id -g) $HOME/.kube/config become: true but i am getting error as below fatal: [ubuntu]: FAILED! => {"changed": t> fatal: [ubuntu]: FAILED! => {"changed": true, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []}rue, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []} EDIT: File module also did not work. - name: Create a symbolic link file: path: $HOME/.kube owner: $(id -u) group: $(id -g)
|
ansible, ansible-2.x, chown
| 19
| 39,603
| 2
|
https://stackoverflow.com/questions/57070583/using-chown-command-in-ansible
|
66,178,118
|
This task (name) has extra params, which is only allowed
|
Having an issue with ansible.builtin.shell and ansible.builtin.command . Probably not using them right, but usage matches the docs examples. Ansible version 2.10.3 In roles/rabbitmq/tasks/main.yml --- # tasks file for rabbitmq # If not shut down cleanly, the following will fix: # systemctl stop rabbitmq-server - name: Stop RabbitMQ service ansible.builtin.service: name: rabbitmq-server state: stopped become: yes # rabbitmqctl force_boot # [URL] # force_boot Ensures that the node will start next time, even if it was not the last to shut down. - name: Force RabbitMQ to boot anyway ansible.builtin.shell: /usr/sbin/rabbitmqctl force_boot # systemctl start rabbitmq-server - name: Stop RabbitMQ service ansible.builtin.service: name: rabbitmq-server state: started become: yes Resulting in the following error: ERROR! this task 'ansible.builtin.shell' has extra params, which is only allowed in the following modules: shell, command, ansible.windows.win_shell, ... The error appears to be in '.../roles/rabbitmq/tasks/main.yml': line 15, > column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: # force_boot Ensures that the node will start next time, even if it was not the last to shut down. - name: Force RabbitMQ to boot anyway ^ here I've tried ansible.builtin.command , both with and without the cmd: parameter. What don't I understand about the usage?
|
This task (name) has extra params, which is only allowed Having an issue with ansible.builtin.shell and ansible.builtin.command . Probably not using them right, but usage matches the docs examples. Ansible version 2.10.3 In roles/rabbitmq/tasks/main.yml --- # tasks file for rabbitmq # If not shut down cleanly, the following will fix: # systemctl stop rabbitmq-server - name: Stop RabbitMQ service ansible.builtin.service: name: rabbitmq-server state: stopped become: yes # rabbitmqctl force_boot # [URL] # force_boot Ensures that the node will start next time, even if it was not the last to shut down. - name: Force RabbitMQ to boot anyway ansible.builtin.shell: /usr/sbin/rabbitmqctl force_boot # systemctl start rabbitmq-server - name: Stop RabbitMQ service ansible.builtin.service: name: rabbitmq-server state: started become: yes Resulting in the following error: ERROR! this task 'ansible.builtin.shell' has extra params, which is only allowed in the following modules: shell, command, ansible.windows.win_shell, ... The error appears to be in '.../roles/rabbitmq/tasks/main.yml': line 15, > column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: # force_boot Ensures that the node will start next time, even if it was not the last to shut down. - name: Force RabbitMQ to boot anyway ^ here I've tried ansible.builtin.command , both with and without the cmd: parameter. What don't I understand about the usage?
|
ansible
| 19
| 38,947
| 3
|
https://stackoverflow.com/questions/66178118/this-task-name-has-extra-params-which-is-only-allowed
|
55,411,080
|
YAML Multiline String While Retaining Indentation and Newlines
|
Background: This is an Ansible playbook using templates to CONSTRUCT a yaml file from a template. So basically I have a jinja2 template file with a line as such: private_key: {{ myvar }} Ansible uses yaml to define the variables. So I will fill in the myvar value something like this. Here I am using the | special character to define a multiline string: myvar: | - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----" However the output trims off the indentation: private_key: - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----" Since the output file is a yaml itself, I need to retain the indentation. It seems no matter what I'll lose the indent. I need the end result to look EXACTLY like this: private_key: - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----"
|
YAML Multiline String While Retaining Indentation and Newlines Background: This is an Ansible playbook using templates to CONSTRUCT a yaml file from a template. So basically I have a jinja2 template file with a line as such: private_key: {{ myvar }} Ansible uses yaml to define the variables. So I will fill in the myvar value something like this. Here I am using the | special character to define a multiline string: myvar: | - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----" However the output trims off the indentation: private_key: - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----" Since the output file is a yaml itself, I need to retain the indentation. It seems no matter what I'll lose the indent. I need the end result to look EXACTLY like this: private_key: - "-----BEGIN PRIVATE KEY-----" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf" - "zzzzzzzzzzzzzzzzzz=" - "-----END PRIVATE KEY-----"
|
ansible, yaml, jinja2
| 19
| 16,220
| 3
|
https://stackoverflow.com/questions/55411080/yaml-multiline-string-while-retaining-indentation-and-newlines
|
38,632,170
|
ERROR! 'file' is not a valid attribute for a Play
|
new playbook test is not working. Newbie to ansible but have read throuugh the docs , samples etc. What is wrong ? ERROR! 'file' is not a valid attribute for a Play The error appears to have been in '/home/NTNET/mresnick/testdel.yml' : line 10, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - file: "path=/tmp/{{ item }} state=absent recurse=no" ^ here --- - name: test playbooktestdel - hosts: temp3 tasks: - name: "delete old files Aveksa" - file: path=/tmp/{{ item }} state=absent recurse=no with_items: - { Aveksa.tar } - { sudo_commands } - { baz } ...
|
ERROR! 'file' is not a valid attribute for a Play new playbook test is not working. Newbie to ansible but have read throuugh the docs , samples etc. What is wrong ? ERROR! 'file' is not a valid attribute for a Play The error appears to have been in '/home/NTNET/mresnick/testdel.yml' : line 10, column 3, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - file: "path=/tmp/{{ item }} state=absent recurse=no" ^ here --- - name: test playbooktestdel - hosts: temp3 tasks: - name: "delete old files Aveksa" - file: path=/tmp/{{ item }} state=absent recurse=no with_items: - { Aveksa.tar } - { sudo_commands } - { baz } ...
|
ansible
| 19
| 45,154
| 1
|
https://stackoverflow.com/questions/38632170/error-file-is-not-a-valid-attribute-for-a-play
|
28,489,705
|
How to assign a random number to a variable in ansible?
|
This is an ansible script that I was expecting to print out the same random number three times. Instead, it prints out three random numbers. How do I assign a random number to a variable in ansible so that it is fixed throughout the playbook? --- - name: Test random filter hosts: localhost gather_facts: False vars: random_number: "{{ 100 | random }}" tasks: - name: Print the random number debug: var=random_number - name: Print the random number debug: var=random_number - name: Print the random number debug: var=random_number
|
How to assign a random number to a variable in ansible? This is an ansible script that I was expecting to print out the same random number three times. Instead, it prints out three random numbers. How do I assign a random number to a variable in ansible so that it is fixed throughout the playbook? --- - name: Test random filter hosts: localhost gather_facts: False vars: random_number: "{{ 100 | random }}" tasks: - name: Print the random number debug: var=random_number - name: Print the random number debug: var=random_number - name: Print the random number debug: var=random_number
|
ansible
| 19
| 33,834
| 2
|
https://stackoverflow.com/questions/28489705/how-to-assign-a-random-number-to-a-variable-in-ansible
|
41,521,138
|
Ansible template adds 'u' to array in template
|
I have the following vars inside of my ansible playbook I got the following structure domains: - { main: 'local1.com', sans: ['test.local1.com', 'test2.local.com'] } - { main: 'local3.com' } - { main: 'local4.com' } And have the following inside of the my conf.j2 {% for domain in domains %} [[acme.domains]] {% for key, value in domain.iteritems() %} {% if value is string %} {{ key }} = "{{ value }}" {% else %} {{ key }} = {{ value }} {% endif %} {% endfor %} {% endfor %} Now when I go in the VM and see the file I get the following: Output [[acme.domains]] main = "local1.com sans = [u'test.local1.com', u'test2.local.com'] [[acme.domains]] main = "local3.com" [[acme.domains]] main = "local4.com" Notice the u inside of the sans array. Excpeted output [[acme.domains]] main = "local1.com" sans = ["test.local1.com", "test2.local.com"] [[acme.domains]] main = "local3.com" [[acme.domains]] main = "local4.com" Why is this happening and how can I fix it?
|
Ansible template adds 'u' to array in template I have the following vars inside of my ansible playbook I got the following structure domains: - { main: 'local1.com', sans: ['test.local1.com', 'test2.local.com'] } - { main: 'local3.com' } - { main: 'local4.com' } And have the following inside of the my conf.j2 {% for domain in domains %} [[acme.domains]] {% for key, value in domain.iteritems() %} {% if value is string %} {{ key }} = "{{ value }}" {% else %} {{ key }} = {{ value }} {% endif %} {% endfor %} {% endfor %} Now when I go in the VM and see the file I get the following: Output [[acme.domains]] main = "local1.com sans = [u'test.local1.com', u'test2.local.com'] [[acme.domains]] main = "local3.com" [[acme.domains]] main = "local4.com" Notice the u inside of the sans array. Excpeted output [[acme.domains]] main = "local1.com" sans = ["test.local1.com", "test2.local.com"] [[acme.domains]] main = "local3.com" [[acme.domains]] main = "local4.com" Why is this happening and how can I fix it?
|
ansible, jinja2, ansible-2.x, ansible-template
| 19
| 36,181
| 1
|
https://stackoverflow.com/questions/41521138/ansible-template-adds-u-to-array-in-template
|
22,978,319
|
how to use ansible b64encode
|
I need to do base64 encoding of something like: " [URL] ". Because there is a colon in that string, I need to enclose everything in quotes. So I have something like: - name: do the encode shell: 'echo "[URL] | /usr/bin/base64' register: bvalue But I get a blank when I use: {{ bvalue.stdout }} So I want to use the Ansible construct, but I don't know how and the documentation is not clear. It's something like: - name: do the encode shell: '{{ "[URL] | b64encode }}' But I know that is wrong. And I can't find any examples. Help!
|
how to use ansible b64encode I need to do base64 encoding of something like: " [URL] ". Because there is a colon in that string, I need to enclose everything in quotes. So I have something like: - name: do the encode shell: 'echo "[URL] | /usr/bin/base64' register: bvalue But I get a blank when I use: {{ bvalue.stdout }} So I want to use the Ansible construct, but I don't know how and the documentation is not clear. It's something like: - name: do the encode shell: '{{ "[URL] | b64encode }}' But I know that is wrong. And I can't find any examples. Help!
|
base64, ansible
| 19
| 34,578
| 2
|
https://stackoverflow.com/questions/22978319/how-to-use-ansible-b64encode
|
60,209,185
|
Ansible - environment variables from .env file
|
I am trying to setup a playbook which will run the command to check status of the service installed in the target machine. The command will only work only if the .env file executed. The command to execute the .env file is .<space>./.env_file_name and the file contains list of environment variables like export JAVA_HOME=/optware/java/jdk/1.2. I tried to execute the environment file before running the command with the below playbook, but it is not working. - hosts: name tasks: - name: execute env file command: . ./.env_file_name register: result Is there any playbook to run the executable environment file to set the environments present on the target machine and then run our command??
|
Ansible - environment variables from .env file I am trying to setup a playbook which will run the command to check status of the service installed in the target machine. The command will only work only if the .env file executed. The command to execute the .env file is .<space>./.env_file_name and the file contains list of environment variables like export JAVA_HOME=/optware/java/jdk/1.2. I tried to execute the environment file before running the command with the below playbook, but it is not working. - hosts: name tasks: - name: execute env file command: . ./.env_file_name register: result Is there any playbook to run the executable environment file to set the environments present on the target machine and then run our command??
|
ansible, environment-variables
| 19
| 41,198
| 3
|
https://stackoverflow.com/questions/60209185/ansible-environment-variables-from-env-file
|
27,569,458
|
How can I ignore failures to decrypt a vaulted file?
|
I have two roles, one of which has a group_vars file that is vaulted, and another that is not. I would like to run the role that does not require any vaulted information, but ansible prompts me for a vault password anyway: $ tree βββ deploy-home-secure.yml βββ deploy-home.yml βββ group_vars β βββ home β β βββ unvaulted β βββ home-secure β βββ unvaulted β βββ vaulted βββ hosts βββ roles βββ home β βββ tasks β βββ main.yaml βββ home-secure βββ tasks βββ main.yaml $ ansible-playbook --version ansible-playbook 1.8.2 configured module search path = None $ ansible-playbook -i hosts deploy-home.yml ERROR: A vault password must be specified to decrypt vaulttest/group_vars/home-secure/vaulted $ ansible-playbook --vault-password-file=/dev/null -i hosts deploy-home.yml ERROR: Decryption failed
|
How can I ignore failures to decrypt a vaulted file? I have two roles, one of which has a group_vars file that is vaulted, and another that is not. I would like to run the role that does not require any vaulted information, but ansible prompts me for a vault password anyway: $ tree βββ deploy-home-secure.yml βββ deploy-home.yml βββ group_vars β βββ home β β βββ unvaulted β βββ home-secure β βββ unvaulted β βββ vaulted βββ hosts βββ roles βββ home β βββ tasks β βββ main.yaml βββ home-secure βββ tasks βββ main.yaml $ ansible-playbook --version ansible-playbook 1.8.2 configured module search path = None $ ansible-playbook -i hosts deploy-home.yml ERROR: A vault password must be specified to decrypt vaulttest/group_vars/home-secure/vaulted $ ansible-playbook --vault-password-file=/dev/null -i hosts deploy-home.yml ERROR: Decryption failed
|
ansible, ansible-vault
| 19
| 14,612
| 4
|
https://stackoverflow.com/questions/27569458/how-can-i-ignore-failures-to-decrypt-a-vaulted-file
|
44,267,060
|
Ansible: [WARNING]: Found both group and host with same name
|
Using the ec2.py inventory script to query against my EC2 instances. I keep getting the following warning signs. How can i suppress them by fixing what's causing the issue? [WARNING]: Found both group and host with same name: nex-1.XYZ.net [WARNING]: Found both group and host with same name: admin-1.XYZ.net [WARNING]: Found both group and host with same name: jenkinsmaster-1.XYZ.net
|
Ansible: [WARNING]: Found both group and host with same name Using the ec2.py inventory script to query against my EC2 instances. I keep getting the following warning signs. How can i suppress them by fixing what's causing the issue? [WARNING]: Found both group and host with same name: nex-1.XYZ.net [WARNING]: Found both group and host with same name: admin-1.XYZ.net [WARNING]: Found both group and host with same name: jenkinsmaster-1.XYZ.net
|
ansible, ansible-inventory
| 19
| 20,086
| 3
|
https://stackoverflow.com/questions/44267060/ansible-warning-found-both-group-and-host-with-same-name
|
64,723,019
|
What is difference between running the commands ansible and ansible-playbook
|
When looking at examples for how to define and run ansible scripts, some examples use ansible command to execute the scripts and some examples use ansible-playbook command. But I have been unable to find the difference between them or guidelines regarding which one to use when. What are the differences between the two commands?
|
What is difference between running the commands ansible and ansible-playbook When looking at examples for how to define and run ansible scripts, some examples use ansible command to execute the scripts and some examples use ansible-playbook command. But I have been unable to find the difference between them or guidelines regarding which one to use when. What are the differences between the two commands?
|
ansible
| 19
| 8,724
| 1
|
https://stackoverflow.com/questions/64723019/what-is-difference-between-running-the-commands-ansible-and-ansible-playbook
|
38,120,793
|
Ansible group vars priority
|
Let's say I have 3 files in group_vars: abc.yml all.yml xyz.yml And the same variable defined in them: - my_var: abc - my_var: all - my_var: xyz Ansible documentation says: Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a playβs vars: section, the 2nd one wins. Does it mean that load order is alphabetical one and abc.yml has the lowest priority, whereas xyz.yml the highest, or it depends on order of groups in hosts ? What is the loading order? It is interesting, that changing the order of groups in hosts changes results as well, but in unpredictable way. I tried running ansible-playbook my_var.yml -c local (that only returns variable value) with all the combinations of: [all] localhost [xyz] localhost [abc] localhost but I still cannot figure out how it works.
|
Ansible group vars priority Let's say I have 3 files in group_vars: abc.yml all.yml xyz.yml And the same variable defined in them: - my_var: abc - my_var: all - my_var: xyz Ansible documentation says: Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a playβs vars: section, the 2nd one wins. Does it mean that load order is alphabetical one and abc.yml has the lowest priority, whereas xyz.yml the highest, or it depends on order of groups in hosts ? What is the loading order? It is interesting, that changing the order of groups in hosts changes results as well, but in unpredictable way. I tried running ansible-playbook my_var.yml -c local (that only returns variable value) with all the combinations of: [all] localhost [xyz] localhost [abc] localhost but I still cannot figure out how it works.
|
variables, ansible, redefinition
| 19
| 13,550
| 3
|
https://stackoverflow.com/questions/38120793/ansible-group-vars-priority
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.