question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
I'm trying to restart the server and then wait, using this:
- name: Restart server
shell: reboot
- name: Wait for server to restart
wait_for:
port=22
delay=1
timeout=300
But I get this error:
TASK: [iptables | Wait for server to restart] *********************************
fatal: [example.com] => faile... | Ansible >= 2.7 (released in Oct 2018)
Use the built-in reboot module:
- name: Wait for server to restart
reboot:
reboot_timeout: 3600
Ansible < 2.7
Restart as a task
- name: restart server
shell: 'sleep 1 && shutdown -r now "Reboot triggered by Ansible" && sleep 1'
async: 1
poll: 0
become: true
This run... | Ansible | 23,877,781 | 47 |
I have the following /etc/ansible/hosts:
[ESNodes]
isk-vsrv643
isk-vsrv644
isk-vsrv645
[PerfSetup]
isk-dsrv613
isk-dsrv614
I know there is an option to run a playbook on particular hosts with -l
Is there a way to run a playbook only on the PerfSetup group?
| Same way as you would do for hosts : -l PerfSetup
| Ansible | 22,129,422 | 47 |
I would expect this to be pretty simple. I'm using the lineinfile module like so:
- name: Update bashrc for PythonBrew for foo user
lineinfile:
dest=/home/foo/.bashrc
backup=yes
line="[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}"
owner=foo
regexp='^'
state=present
... | The Ansible discussion group helped get me sorted out on this. The problem is the regexp parameter.
Since I only want the line appended to the file once, I need the regexp to match the line as closely as possible. This is complicated in my case by the fact that my line includes variables. But, assuming the line starte... | Ansible | 19,688,885 | 47 |
I want to setup a MySQL server on AWS, using Ansible for the configuration management.
I am using the default AMI from Amazon (ami-3275ee5b), which uses yum for package management.
When the Playbook below is executed, all goes well. But when I run it for a second time, the task Configure the root credentials fails, bec... | I posted about this on coderwall, but I'll reproduce dennisjac's improvement in the comments of my original post.
The trick to doing it idempotently is knowing that the mysql_user module will load a ~/.my.cnf file if it finds one.
I first change the password, then copy a .my.cnf file with the password credentials. When... | Ansible | 16,444,306 | 47 |
Say I have this dictionary
war_files:
server1:
- file1.war
- file2.war
server2:
- file1.war
- file2.war
- file3.war
and for now I just want to loop over each item (key), and then over each item in the key (value). I did this
- name: Loop over the dictionary
debug: msg="Key={{ item.key }} value={{ item.... | Hows this
- hosts: localhost
vars:
war_files:
server1:
- file1.war
- file2.war
server2:
- file1.war
- file2.war
- file3.war
tasks:
- name: Loop over subelements of the dictionary
debug:
msg: "Key={{ item.0.key }} value={{ item.1 }}"
loop: "{{ war... | Ansible | 42,167,747 | 46 |
I want to get the service status, such as redis-server by Ansible.
I know how to use Ansible service module to stop or start system service.
But how can I get the current service status?
| You can also use the service_facts module.
Example usage:
- name: collect facts about system services
service_facts:
register: services_state
- name: Debug
debug:
var: services_state
Example output:
TASK [Debug] ******************************************************
ok: [local] => {
"services_state": {
... | Ansible | 38,847,824 | 46 |
I am trying to write an Ansible playbook that only compiles Nginx if it's not already present and at the current version. However it compiles every time which is undesirable.
This is what I have:
- shell: /usr/local/nginx/sbin/nginx -v 2>&1
register: nginxVersion
- debug:
var=nginxVersion
- name: install nginx
... | Try:
when: nginxVersion.stdout != 'nginx version: nginx/1.8.0'
or
when: '"nginx version: nginx/1.8.0" not in nginxVersion.stdout'
| Ansible | 32,786,122 | 46 |
my inventory file's contents -
[webservers]
x.x.x.x ansible_ssh_user=ubuntu
[dbservers]
x.x.x.x ansible_ssh_user=ubuntu
in my tasks file which is in common role i.e. it will run on both hosts but I want to run a following task on host webservers not in dbservers which is defined in inventory file
- name: Install requ... | If you want to run your role on all hosts but only a single task limited to the webservers group, then - like you already suggested - when is your friend.
You could define a condition like:
when: inventory_hostname in groups['webservers']
| Ansible | 31,912,748 | 46 |
Does anyone have an example of decrypting and uploading a file using ansible-vault.
I am thinking about keeping my ssl certificates encrypted in source control.
It seems something like the following should work.
---
- name: upload ssl crt
copy: src=../../vault/encrypted.crt dest=/usr/local/etc/ssl/domain.crt
| The copy module now does this seamlessly as of Ansible 2.1.x. Just encrypt your file with Ansible Vault and then issue the copy task on the file.
(For reference, here's the feature that added this: https://github.com/ansible/ansible/pull/15417)
| Ansible | 22,773,294 | 46 |
This seems like it should be really simple:
tasks:
- name: install python packages
pip: name=${item} virtualenv=~/buildbot-env
with_items: [ buildbot ]
- name: create buildbot master
command: buildbot create-master ~/buildbot creates=~/buildbot/buildbot.tac
However, the command will not succeed unless the virtua... | The better way is to use the full path to installed script - it will run in its virtualenv automatically:
tasks:
- name: install python packages
pip: name={{ item }} virtualenv={{ venv }}
with_items: [ buildbot ]
- name: create buildbot master
command: "{{ venv }}/bin/buildbot create-master ~/buildbot
... | Ansible | 20,040,141 | 46 |
What is the difference between
vars_files directive
and
include_vars module
Which should be used when, is any of above deprecated, discouraged?
| Both vars_files and include_vars are labeled as stable interfaces so neither of them are deprecated. Both of them have some commonalities but they solve different purposes.
vars_files:
vars_file directive can only be used when defining a play to specify variable files. The variables from those files are included in the... | Ansible | 53,253,879 | 45 |
In Ansible, there are several places where variables can be defined: in the inventory, in a playbook, in variable files, etc. Can anyone explain the following observations that I have made?
When defining a Boolean variable in an inventory, it MUST be capitalized (i.e., True/False), otherwise (i.e., true/false) it wil... | Variables defined in YAML files (playbooks, vars_files, YAML-format inventories)
YAML principles
Playbooks, vars_files, and inventory files written in YAML are processed by a YAML parser first. It allows several aliases for values which will be stored as Boolean type: yes/no, true/false, on/off, defined in several cas... | Ansible | 47,877,464 | 45 |
I'm trying insert a line in a property file using ansible.
I want to add some property if it does not exist, but not replace it if such property already exists in the file.
I add to my ansible role
- name: add couchbase host to properties
lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbas... | The lineinfile module ensures the line as defined in line is present in the file and the line is identified by your regexp. So no matter what value your setting already has, it will be overridden by your new line.
If you don't want to override the line you first need to test the content and then apply that condition to... | Ansible | 29,075,287 | 45 |
How can I run a playbook in python script? What is the equivalent of the following using ansible module in python:
ansible -i hosts dbservers -m setup
ansible-playbook -i hosts -vvvv -k site.yml
I was looking at their documenation in http://docs.ansible.com/developing_api.html but they have very limited examples.
| Deprecation Notice: This post doesn't work as of Ansible 2. The API was changed.
This is covered in the Ansible documentation under "Python API."
For example, ansible -i hosts dbservers -m setup is implemented via:
import ansible.runner
runner = ansible.runner.Runner(
module_name='setup',
module_args='',
patt... | Ansible | 27,590,039 | 45 |
Below is the jinja2 template that i wrote to use in ansible.
{% set port = 1234 %}
{% set server_ip = [] %}
{% for ip in host_ip %}
{% do server_ip.append({{ ip }}:{{ port }}) %}
{% endfor %}
{% server_ip|join(', ') %}
Below is the my desired output:
devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234
... | Try below code:
{% set port = '1234' %}
{% set server_ip = [] %}
{% for ip in host_ip %}
{{ server_ip.append( ip+":"+port ) }}
{% endfor %}
{{ server_ip|join(',') }}
You ll get:
192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234
| Ansible | 49,619,445 | 44 |
I'm working on automating a task which needs to append the latest version of software to a file. I don't want it to do this multiple times for the same version.
It looks at the following example file:
var software releases = new Array(
"4.3.0",
"4.4.0",
"4.5.0",
"4.7.0",
"4.8.0",
"4.11.0",
"... | As nikobelia pointed out in the comments, grep returns an exit code of 1 when it doesn't match any lines. Ansible then interprets this (actually any status code other than 0 from a shell/command task) as an error and so promptly fails.
You can tell Ansible to ignore the response code from the shell/command task by usin... | Ansible | 34,340,562 | 44 |
Is it possible to call a role multiple times in a loop like this:
vars:
my_array:
- foo
- bar
- baz
roles:
- role: foobar
with_items: my_array
How can we do this?
| Now supported as of Ansible 2.3.0:
- name: myrole
with_items:
- "aone"
- "atwo"
include_role:
name: myrole
vars:
thing: "{{ item }}"
| Ansible | 33,415,992 | 44 |
is it possible to append a variable list to a static list in ansible?
I can define the whole list as a variable:
my_list:
- 1
- 2
- 3
and then use it in a playbook as
something: {{my_list}}
But I cannot seem to find how to do this (pseudo code):
list_to_append:
- 3
- 4
and then in the playbook:
something... | If you really want to append to content, you will need to use the set_fact module. But if you just want to use the merged lists it is as easy as this:
{{ list1 + list2 }}
With set_fact it would look like this:
- set_fact:
list_merged: "{{ list1 + list2 }}"
NOTE: If you need to do additional operations on the conc... | Ansible | 31,045,106 | 44 |
I'd like to see the actual git commit changes in the ansible vault file.
Is there an easy way how to achieve this?
| You can do this very neatly, so that the normal git tools like git log and git diff can see inside the vaulted files, using a custom git diff driver and .gitattributes.
Make sure that your vault password is in .vault_password and that that file is not committed - you should also add it to .gitignore.
Add a .gitattribu... | Ansible | 29,937,195 | 44 |
Based on extra vars parameter I Need to write variable value in ansible playbook
ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3"
If only param1 passed
myvariable: 'param1'
If only param1,param2 passed
myvariable: 'param1,param2'
If param1,param2,param3 are passed then variable value w... | I am sure there is a smarter way for doing what you want but this should work:
- name : Test var
hosts : all
gather_facts : no
vars:
myvariable : false
tasks:
- name: param1
set_fact:
myvariable: "{{param1}}"
when: param1 is defined
- name: param2
set_fact:
... | Ansible | 23,264,226 | 44 |
If any Ansible task fails, there is error output, the playbook will display it newlines escaped '\n'. For tracebacks, spanning multiple lines, this make it very hard to read.
Is there a way to make ansible-playbook to display unescaped error output from shell, pip, gitand other similar tasks?
| Add stdout_callback=debug and stderr_callback=debug in the defaults section of your ansible.cfg file.
[defaults]
(...)
stdout_callback=debug
stderr_callback=debug
This is supported by ansible > 2.0
| Ansible | 37,171,966 | 43 |
I am running an ansible-playbook which have many tasks listed. All of them use to get run one by one, but I want to pause the playbook after a particular tasks to asks the user if he wants to continue running the rest of the tasks or exit. I have seen the pause module of ansible but couldn't see any example which asks ... | The pause module actually does exactly that. But it does not give you an option to answer yes or no. Instead it expects the user to press Ctrl+C and then a for abort. To continue the user simply needs to press Enter.
Since this is not perfectly obvious to the user you can describe it in the prompt parameter.
- name: Ex... | Ansible | 34,290,525 | 43 |
I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far i... | An update:
In 2.0 you are able to use with_ loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’s own with_ loop will overwrite the value of the special item variabl... | Ansible | 30,785,281 | 43 |
Is it possible to set a fact containing a list in Ansible using set_fact? What's the correct syntax for it?
| Yes, this is possible. As mentioned in another answer, you can set an array using double quotes, like so:
- name: set foo fact to a list
set_fact:
foo: "[ 'one', 'two', 'three' ]"
However, I thought I'd create another answer to indicate that it's also possible to add to an existing array, like so:
- name: add ... | Ansible | 23,507,589 | 43 |
I'm just trying to write a basic playbook, and keep getting the error below.
Tried a tonne of things but still can't get it right. I know it must be a syntax thing but no idea where.
This is the code I have:
---
# This playbook runs a basic DF command.
- hosts: nagios
#remote_user: root
tasks:
- name: find disk... | The problem is that without the indentation of the command line, the command directive is part of the overall play, and not the task block.i.e. the command should be part of the task block.
---
# This playbook runs a basic DF command.
- hosts: nagios
#remote_user: root
tasks:
- name: find disk space available.
... | Ansible | 49,246,837 | 42 |
Sometimes, ansible doesn't do what you want. And increasing verbosity doesn't help. For example, I'm now trying to start coturn server, which comes with init script on systemd OS (Debian Jessie). Ansible considers it running, but it's not. How do I look into what's happening under the hood? Which commands are executed,... | Debugging modules
The most basic way is to run ansible/ansible-playbook with an increased verbosity level by adding -vvv to the execution line.
The most thorough way for the modules written in Python (Linux/Unix) is to run ansible/ansible-playbook with an environment variable ANSIBLE_KEEP_REMOTE_FILES set to 1 (on th... | Ansible | 42,417,079 | 42 |
I noticed Ansible removes the temporary script using a semi-colon to separate the bash commands.
Here is an example command:
EXEC ssh -C -tt -v -o ControlMaster=auto -o ControlPersist=60s -o
ControlPath="/Users/devuser/.ansible/cp/ansible-ssh-%h-%p-%r" -o
KbdInteractiveAuthentication=no -o
PreferredAuthentications=g... | I found the environment variable -
export ANSIBLE_KEEP_REMOTE_FILES=1
Set this, then re-run ansible-playbook, and then ssh and cd over to ~/.ansible/tmp/ to find the files.
| Ansible | 30,060,164 | 42 |
I have two ansible tasks as follows
tasks:
- shell: ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d'
register: var1
- debug: var=var1
- shell: ethtool -i {{ item }} | grep bus-info | cut -b 16-22
with_items: var1.stdout_lines
register: var2
- debug: var=var2
which is used to get a list of interfaces in a... | Is this what you're looking for:
Variables registered for a task that has with_items have different format, they contain results for all items.
- hosts: localhost
tags: s21
gather_facts: no
vars:
images:
- foo
- bar
tasks:
- shell: "echo result-{{item}}"
register: "r"
with_item... | Ansible | 29,635,627 | 42 |
I have an ansible variable passed in on the command line as such:
ansible-playbook -e environment=staging ansible/make_server.yml
I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as:
- include_vars: staging_vars.yml
when: environment | s... | Be careful with a variable called environment, it can cause problems because Ansible uses it internally. I can't remember if it's in the docs, but here's a mailing list thread:
https://groups.google.com/forum/#!topic/ansible-project/fP0hX2Za4I0
We use a variable called stage.
It looks like you'll end up with a bunch of... | Ansible | 27,335,204 | 42 |
I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.)
This is not working. It always prompts me.
vars:
THISUSER: "{{ lookup('env','LOGNAME') }}... | According to the replies from the devs and a quick test I've done with the latest version, the vars_prompt is run before "GATHERING FACTS". This means that the env var SSHPWD is always null at the time of your check with when.
Unfortunately it seems there is no way of allowing the vars_prompt statement at task level.
M... | Ansible | 25,466,675 | 42 |
I'm working on a project where having swap memory on my servers is a needed to avoid some python long running processes to go out of memory and realized for the first time that my ubuntu vagrant boxes and AWS ubuntu instances didn't already have one set up.
In https://github.com/ansible/ansible/issues/5241 a possible b... | This is my current solution:
- name: Create swap file
command: dd if=/dev/zero of={{ swap_file_path }} bs=1024 count={{ swap_file_size_mb }}k
creates="{{ swap_file_path }}"
tags:
- swap.file.create
- name: Change swap file permissions
file: path="{{ swap_file_path }}"
owner=root
g... | Ansible | 24,765,930 | 42 |
Having an inventory file like:
[my_hosts]
my_host ansible_ssh_host=123.123.123.123
my_host2 ansible_ssh_host=234.234.234.234
I want to gather some debug information in my templates.
How do I acces the alias variable in a playbook/template?
I.e.:
debug: msg=Myhost is {{ ansible_host_alias }}
# Myhost is my_host
# Myh... | The variable I was searching for is a built in feature: inventory_hostname
Ansible documentation about inventory_hostname and inventory_hostname_short is found from chapter Magic Variables, and How To Access Information About Other Hosts.
Original question: https://groups.google.com/forum/#!topic/ansible-project/Oa5YXj... | Ansible | 22,983,484 | 42 |
I have a simple file at /etc/foo.txt. The file contains the following:
#bar
I have the following ansible playbook task to uncomment the line above:
- name: test lineinfile
lineinfile: backup=yes state=present dest=/etc/foo.txt
regexp='^#bar'
line='bar'
When I first run ansible-playbook, ... | You need to add backrefs=yes if you don't want to change your regular expression.
- name: test lineinfile
lineinfile: backup=yes state=present dest=/etc/foo.txt
regexp='^#bar' backrefs=yes
line='bar'
This changes the behavior of lineinfile from:
find
if found
replace line found
else... | Ansible | 19,390,600 | 42 |
I have this Ansible as a String:
FUBAR={{ PREFIX }}_{{ CNAME }}{{ VERSION }}
I want to replace all . in the concatenated string with '', like this:
FUBAR={{ {{ PREFIX }}_{{ CNAME }}{{ VERSION }} | replace('.','') }}
I get the message:
expected token ':', got '}'
Could anyone give me a suggestion what's wrong?
| FUBAR="{{ ( PREFIX + '_' + CNAME + VERSION ) | replace('.','') }}"
Resolving a few problems:
too many '{{}}'s
need quotes around the whole expression
the replace will only act on the last element unless it is all surrounded by '()'s
| Ansible | 53,671,030 | 41 |
In the best practices page, there is an example that uses hosts.yml for hosts files:
In the docs, however, I can only find the INI syntax for writing hosts files.
What is the syntax for the inventory files in YAML?
| Yes.
It's been deprecated in version 0.6 in 2012 and reintroduced in a commit first included in version 2.1 in 2016.
The example file on GitHub contains the guidelines and examples:
Comments begin with the '#' character
Blank lines are ignored
Top level entries are assumed to be groups
Hosts must be specified in a g... | Ansible | 41,094,864 | 41 |
I'm trying to run ansible role on multiple servers, but i get an error:
fatal: [192.168.0.10]: UNREACHABLE! => {"changed": false, "msg":
"Failed to connect to the host via ssh.", "unreachable": true}
My /etc/ansible/hosts file looks like this:
192.168.0.10 ansible_sudo_pass='passphrase' ansible_ssh_user=user
192.16... | You need to change the ansible_ssh_pass as well or ssh key, for example I am using this in my inventory file:
192.168.33.100 ansible_ssh_pass=vagrant ansible_ssh_user=vagrant
After that I can connect to the remote host:
ansible all -i tests -m ping
With the following result:
192.168.33.100 | SUCCESS => {
"changed... | Ansible | 37,213,551 | 41 |
As far as i know, ansible has an option named --list-hosts for listing hosts. Is there any option for listing host groups? Or any other way to come through?
| You can simply inspect the groups variable using the debug module:
ansible localhost -m debug -a 'var=groups.keys()'
The above is using groups.keys() to get just the list of groups. You could drop the .keys() part to see group membership as well:
ansible localhost -m debug -a 'var=groups'
| Ansible | 33,363,023 | 41 |
As a safeguard against using an outdated playbook, I'd like to ensure that I have an updated copy of the git checkout before Ansible is allowed to modify anything on the servers.
This is how I've attempted to do it. This action is located in a file included by all play books:
- name: Ensure local git repository is up-t... | Updated
When I fist wrote my answer (2014-02-27), Ansible had no built-in support for running a task only once per playbook, not once per affected host that the playbook was run on. However, as tlo writes, support for this was introduced with run_once: true in Ansible version 1.7.0 (released on 2014-08-06). With this... | Ansible | 22,070,232 | 41 |
I have this task in Ansible:
- name: Install mongodb
yum:
name:
- "mongodb-org-{{ mongodb_version }}"
- "mongodb-org-server-{{ mongodb_version }}"
- "mongodb-org-mongos-{{ mongodb_version }}"
- "mongodb-org-shell-{{ mongodb_version }}"
- "mongodb-org-tools-{{ mongodb_version }}"
state: pre... | To my surprise I didn't find the simplest solution in all the answers, so here it is. Referring to the question title Installing multiple packages in Ansible this is (using the yum module):
- name: Install MongoDB
yum:
name:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- m... | Ansible | 54,944,080 | 40 |
Goal:
Create multiple directories if they don't exist.
Don't change permissions of existing folder
Current playbook:
- name: stat directories if they exist
stat:
path: "{{ item }}"
loop:
- /data/directory
- /data/another
register: myvar
- debug:
msg: "{{ myvar.results }}"
- name: create direct... | Using Ansible modules, you don't need to check if something exist or not, you just describe the desired state, so:
- name: create directory if they don't exist
file:
path: "{{ item }}"
state: directory
owner: root
group: root
mode: 0775
loop:
- /data/directory
- /data/another
| Ansible | 42,186,301 | 40 |
I've got a dictionary with different names like
vars:
images:
- foo
- bar
Now, I want to checkout repositories and afterwards build docker images only when the source has changed.
Since getting the source and building the image is the same for all items except the name I created the tasks with with_ite... |
So how can I properly save the results of the operations in variable names based on the list I iterate over?
You don't need to. Variables registered for a task that has with_items have different format, they contain results for all items.
- hosts: localhost
gather_facts: no
vars:
images:
- foo
- b... | Ansible | 29,512,443 | 40 |
How do I use the when statement based on the standard output of register: result? If standard output exists I want somecommand to run if no standard output exists I want someothercommand to run.
- hosts: myhosts
tasks:
- name: echo hello
command: echo hello
register: result
- command: somecommand {{ resu... | Try checking to see it if equals a blank string or not?
- hosts: myhosts
tasks:
- name: echo hello
command: echo hello
register: result
- command: somecommand {{ result.stdout }}
when: result.stdout != ""
- command: someothercommand
when: result.stdout == ""
| Ansible | 26,142,343 | 40 |
I am using Ansible's shell module to find a particular string and store it in a variable. But if grep did not find anything I am getting an error.
Example:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
check_mode: no
When I run this Ansible playbook if http_status string i... | grep by design returns code 1 if the given string was not found. Ansible by design stops execution if the return code is different from 0. Your system is working properly.
To prevent Ansible from stopping playbook execution on this error, you can:
add ignore_errors: yes parameter to the task
use failed_when: parameter... | Ansible | 41,010,378 | 39 |
I am trying to start filebeat (or for that matter any other process which will run continuously on demand) process on multiple hosts using ansible. I don't want ansible to wait till the process keeps on running. I want ansible to fire and forget and come out and keep remote process running in back ground.
I've tried us... | Simplified answer from link I mentioned in the comment:
---
- hosts: centos-target
gather_facts: no
tasks:
- shell: "(cd /; python -mSimpleHTTPServer >/dev/null 2>&1 &)"
async: 10
poll: 0
Note subshell parentheses.
Update: actually, you should be fine without async, just don't forget to redirect s... | Ansible | 39,347,379 | 39 |
I am trying to shrink several chunks of similar code which looks like:
- ... multiple things is going here
register: list_register
- name: Generating list
set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}"
# the same code repeats...
The only difference between them i... | take a look at this sample playbook:
---
- hosts: localhost
vars:
iter:
- key: abc
val: xyz
- key: efg
val: uvw
tasks:
- set_fact: {"{{ item.key }}":"{{ item.val }}"}
with_items: "{{iter}}"
- debug: msg="key={{item.key}}, hostvar={{hostvars['localhost'][item.key]}}"
... | Ansible | 38,143,647 | 39 |
Some ansible commands produce json output that's barely readable for humans. It distracts people when they need to check if playbook executed correctly and causes confusion.
Example commands are shell and replace - they generate a lot of useless noise. How can I prevent this? Simple ok | changed | failed is enough. I d... | Use no_log: true on those tasks where you want to suppress all further output.
- shell: whatever
no_log: true
I believe the only mention of this feature is within the FAQ.
Example playbook:
- hosts:
- localhost
gather_facts: no
vars:
test_list:
- a
- b
- c
tasks:
- name: Test w... | Ansible | 32,475,881 | 39 |
Imagine this ansible playbook:
- name: debug foo
debug: msg=foo
tags:
- foo
- name: debug bar
debug: msg=bar
tags:
- bar
- name: debug baz
debug: msg=baz
tags:
- foo
- bar
How can I run only the debug baz task? I want to say only run tasks which are tagged with foo AND bar. Is that po... | Ansible tags use "or" not "and" as a comparison. Your solution to create yet another tag is the appropriate one.
| Ansible | 30,036,126 | 39 |
I have a custom SSH config file that I typically use as follows
ssh -F ~/.ssh/client_1_config amazon-server-01
Is it possible to assign Ansible to use this config for certain groups? It already has the keys and ports and users all set up. I have this sort of config for multiple clients, and would like to keep the con... | You can set ssh arguments globally in the ansible.cfg:
[ssh_connection]
ssh_args = -F ~/.ssh/client_1_config
Via behavioral inventory parameters you can set it per host or group
amazon-server-01 ansible_ssh_common_args=~/.ssh/client_1_config
| Ansible | 28,553,307 | 39 |
I'm trying to include a file only if it exists. This allows for custom "tasks/roles" between existing "tasks/roles" if needed by the user of my role. I found this:
- include: ...
when: condition
But the Ansible docs state that:
"All the tasks get evaluated, but the conditional is applied to each and every task" - h... | The with_first_found conditional can accomplish this without a stat or local_action. This conditional will go through a list of local files and execute the task with item set to the path of the first file that exists.
Including skip: true on the with_first_found options will prevent it from failing if the file does no... | Ansible | 28,119,521 | 39 |
Is there exists some way to print on console gathered facts ?
I mean gatering facts using setup module. I would like to print gathered facts. Is it possible ? If it is possible can someone show example?
| Use setup module as ad-hoc command:
ansible myhost -m setup
| Ansible | 49,677,591 | 38 |
I am a newbie to ansible and I am using a very simple playbook to issue sudo apt-get update and sudo apt-get upgrade on a couple of servers.
This is the playbook I am using:
---
- name: Update Servers
hosts: my-servers
become: yes
become_user: root
tasks:
- name: update packages
apt: update_cache=yes... | You need to create some vaulted variable files and then either include them in your playbooks or on the command line.
If you change your inventory file to use a variable for the become pass this variable can be vaulted:
[my-servers]
san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass='{{ ... | Ansible | 37,297,249 | 38 |
I have a task:
- name: uploads docker configuration file
template:
src: 'docker.systemd.j2'
dest: '/etc/systemd/system/docker.service'
notify:
- daemon reload
- restart docker
in Ansible playbook's documentation, there is a sentence:
Notify handlers are always run in the order written.
So, it is ... | I think you may have “restart docker” listed before “daemon reload” in your handlers file.
That part of the ansible documentation is a bit misleading. It means that handlers are executed in the order they are written in the handlers file, not the order they are notified.
This is little more clear in the documentation:
... | Ansible | 35,130,051 | 38 |
I'm looking for the way how to make Ansible to analyze playbooks for required and mandatory variables before run playbook's execution like:
- name: create remote app directory hierarchy
file:
path: "/opt/{{ app_name | required }}/"
state: directory
owner: "{{ app_user | required }}"
group: "{{ app_use... | As Arbab Nazar mentioned, you can use {{ variable | mandatory }} (see Forcing variables to be defined) inside Ansible task.
But I think it looks nicer to add this as first task, it checks is app_name, app_user and app_user_group exist:
- name: 'Check mandatory variables are defined'
assert:
that:
- app_name... | Ansible | 45,013,306 | 37 |
I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.
I have a series of items which all take the form of <word><number> such as aaa01, aaa141, bbb05.
The idea was to parse the word and number(ign... | You need to cast string to int after regex'ing number:
{% set number = get_host_number() | int %}
And then there is no need in | int inside get_host_range macro.
| Ansible | 39,938,323 | 37 |
Consider if I want to check something quickly. Something that doesn't really need connecting to a host (to check how ansible itself works, like, including of handlers or something). Or localhost will do. I'd probably give up on this, but man page says:
-i PATH, --inventory=PATH
The PATH to the inventory, which default... | Prerequisites. You need to have ssh server running on the host (ssh localhost should let you in).
Then if you want to use password authentication (do note the trailing comma):
$ ansible-playbook playbook.yml -i localhost, -k
In this case you also need sshpass.
In case of public key authentication:
$ ansible-playbook p... | Ansible | 38,187,557 | 37 |
I have an ansible file (my_file.yml) that looks something like this:
---
- name: The name
hosts: all
tasks:
- include:my_tasks.yml
vars:
my_var: "{{ my_var }}"
my_tasks.yml looks like this:
- name: Install Curl
apt: pkg=curl state=installed
- name: My task
command: bash -c "curl -sSL http... | Faced the same issue in my project. It turns out that the variable name in the playbook and the task have to be different.
---
- name: The name
hosts: all
vars:
my_var_play: "I need to send this value to the task"
some_other_var: "This is directly accessible in task"
tasks:
- include:my_tasks.yml
... | Ansible | 32,232,221 | 37 |
I have written a simple playbook to print java process ID and other information of that PID
[root@server thebigone]# cat check_java_pid.yaml
---
- hosts: all
gather_facts: no
tasks:
- name: Check PID of existing Java process
shell: "ps -ef | grep [j]ava"
register: java_status
- debug: var=jav... | Here you have examples in official documentation.
https://docs.ansible.com/ansible/2.4/playbooks_reuse_includes.html
I had same error as yours after applying the aproved answer. I resolved problem by creating master playbook like this:
---
- import_playbook: master-okd.yml
- import_playbook: infra-okd.yml
- import_play... | Ansible | 43,609,132 | 36 |
I'm trying to run a python script from an ansible script. I would think this would be an easy thing to do, but I can't figure it out. I've got a project structure like this:
playbook-folder
roles
stagecode
files
mypythonscript.py
tasks
main.yml
release.yml
I'm trying to run mypython... | try to use script directive, it works for me
my main.yml
---
- name: execute install script
script: get-pip.py
and get-pip.py file should be in files in the same role
| Ansible | 35,139,711 | 36 |
I am looking for something that would be similar to with_items: but that would get the list of items from a file instead of having to include it in the playbook file.
How can I do this in ansible?
| Latest Ansible recommends loop instead of with_something. It can be used in combination with lookup and splitlines(), as Ikar Pohorský pointed out:
- debug: msg="{{item}}"
loop: "{{ lookup('file', 'files/branches.txt').splitlines() }}"
files/branches.txt should be relative to the playbook
| Ansible | 33,541,870 | 36 |
I have an object like that
objs:
- { key1: value1, key2: [value2, value3] }
- { key1: value4, key2: [value5, value6] }
And I'd like to create the following files
value1/value2
value1/value3
value4/value5
value4/value6
but I have no idea how to do a double loop using with_items
| Take a look at with_subelements in Ansible's docs for loops.
You need to create directories:
Iterate though objs and create files:
Here is an example:
---
- hosts: localhost
gather_facts: no
vars:
objs:
- { key1: value1, key2: [ value2, value3] }
- { key1: value4, key2: [ value5, value6] }
task... | Ansible | 31,566,568 | 36 |
I am trying to install Bundler on my VPS using Ansible.
I already have rbenv set up and the global ruby is 2.1.0.
If I SSH as root into the server and run gem install bundler, it installs perfectly.
I have tried the following three ways of using Ansible to install the Bundler gem and all three produce no errors, but wh... | The problem is that, when running gem install bundler via ansible, you're not initializing rbenv properly, since rbenv init is run in .bashrc or .bash_profile. So the gem command used is the system one, not the one installed as a rbenv shim. So whenever you install a gem, it is installed system-wide, not in your rbenv ... | Ansible | 22,115,936 | 36 |
In some ansible roles (e.g. roles/my-role/) I've got quite some big default variables files (defaults/main.yml). I'd like to split the main.yml into several smaller files. Is it possible to do that?
I've tried creating the files defaults/1.yml and defaults/2.yml, but they aren't loaded by ansible.
| The feature I'm describing below has been available since Ansible 2.6, but got a bugfix in v2.6.2 and another (minor) one in v2.7.
To see a solution for older versions, see Paul's answer.
defaults/main/
Instead of creating defaults/main.yml, create a directory — defaults/main/ — and place all YAML files in there.
def... | Ansible | 51,818,264 | 35 |
What is the difference between using with_items vs loops in ansilbe?
| Update: The most recent Documentation lists down the differences as below
The with_ keywords rely on Lookup Plugins - even items is a lookup.
The loop keyword is equivalent to with_list, and is the best choice for simple loops.
The loop keyword will not accept a string as input, see Ensuring list input for ... | Ansible | 50,456,997 | 35 |
I want to pip install with --upgrade, using Ansible.
What's the syntax?
| - name: install the package, force upgrade
pip:
name: <your package name>
state: latest
Or with:
- name: install the package, force reinstall to the latest version
pip:
name: <your package name>
state: forcereinstall
| Ansible | 47,632,103 | 35 |
I have a problem to find a working solution to loop over my inventory.
I start my playbook with linking a intentory file:
ansible-playbook -i inventory/dev.yml playbook.yml
My playbook looks like this:
---
- hosts: localhost
tasks:
- name: Create VM if enviro == true
include_role:
name: local_vm_c... | If the only problem is with_items loop, replace it with:
with_items: "{{ groups['local_vm'] }}"
and you are good to go. Bare variables are not supported in with_ any more.
| Ansible | 43,140,086 | 35 |
Is there a way to render Ansible template into the fact? I tried to find a solution but it looks like temp file is the the only way.
| I think you might be just looking for the template lookup plugin:
- set_fact:
rendered_template: "{{ lookup('template', './template.j2') }}"
Usage example:
template.j2
Hello {{ value_for_template }}
playbook.yml
---
- hosts: localhost
gather_facts: no
connection: local
vars:
value_for_t... | Ansible | 41,424,999 | 35 |
I found this blockinfile issue, where a user suggested adding a number after the "|" in the "block: |" line, but gives a syntax error. Basically, I want to use blockinfile module to add a block of lines in a file, but I want the block to be indented 6 spaces in the file. Here's the task
- name: Added a block of lines i... | You can use a YAML feature called "Block Indentation Indicator":
- name: Added a block of lines in the file
blockinfile:
dest: /path/some_file.yml
insertafter: 'authc:'
block: |2
line0
line1
line2
line3
line4
It's all about the 2 after the |
References:
https://groups.g... | Ansible | 39,731,999 | 35 |
Is it possible to check if a string exists in a file using Ansible?
I want to check is a user has access to a server. This can be done on the server using cat /etc/passwd | grep username, but I want Ansible to stop if the user is not there.
I have tried to use the lineinfile but can't seem to get it to return.
- name: ... | It's a tricky one. the lineinfile module is specifically intended for modifying the content of a file, but you can use it for a validation check as well.
- name: find
lineinfile:
dest: /etc/passwd
line: "user"
check_mode: yes
register: presence
failed_when: presence.changed
check_mode ensures it never... | Ansible | 38,461,920 | 35 |
I configured nginx installation and configuration (together with setup SSL certificates for https site) via ansible. SSL certificates are under passphrases.
I want to write ansilbe task which is restarting nginx. The problem is the following.
Normally, nginx with https site inside asks for PEM pass phrase during resta... | Nginx has ssl_password_file parameter.
Specifies a file with passphrases for secret keys where each passphrase is specified on a separate line. Passphrases are tried in turn when loading the key.
Example:
http {
ssl_password_file /etc/keys/global.pass;
...
server {
server_name www1.example.com;
... | Ansible | 33,084,347 | 35 |
By looking around here as well as the internet in general, I have found Bouncy Castle. I want to use Bouncy Castle (or some other freely available utility) to generate a SHA-256 Hash of a String in Java. Looking at their documentation I can't seem to find any good examples of what I want to do. Can anybody here help me... | To hash a string, use the built-in MessageDigest class:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
public class CryptoHash {
public static void main(String[] args) throws NoSuchAlgorithmException {
Mess... | Bouncy Castle | 3,103,652 | 120 |
What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libraries. None of these solutions seem to have an easy answer.
| I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).
| Bouncy Castle | 199,624 | 86 |
I need to export private key from Windows store. What should I do if the key is marked as non-exportable? I know that it is possible, program jailbreak can export this key.
To export key I use Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair() that exports key from (RSACryptoServiceProvider)cryptoProv.ExportParamet... | You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable.
But if you patch (in memory) normal APIs, you can use the normal way to export :)
There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)
download (and launch with administrative privileges)... | Bouncy Castle | 3,914,882 | 69 |
I searched around, but I didn't find a clear example.
I want to create a self-signed (self-)trusted certificate programmatically (C#), following these steps:
STEP 1:
Create a root CA certificate on the fly and add it to the certificate store in the folder "Trusted Root certification Authorities"
I want to do exactly wh... | I edited the answer to do the root certificate first and then issue an end entity certificate.
Here is some example of generating a self-signed certificate through Bouncy Castle:
public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, in... | Bouncy Castle | 22,230,745 | 54 |
In versions prior to r146 it was possible to create X509Certificate objects directly.
Now that API is deprecated and the new one only deliveres a X509CertificateHolder object.
I cannot find a way to transform a X509CertificateHolder to X509Certificate.
How can this be done?
| I will answer to my own questions, but not delete it, in case someone else got the same problems:
return new JcaX509CertificateConverter().getCertificate(certificateHolder);
And for attribute certificates:
return new X509V2AttributeCertificate(attributeCertificateHolder.getEncoded());
Not nice, as it is encoding and ... | Bouncy Castle | 6,370,368 | 50 |
My application will take a set of files and sign them. (I'm not trying to sign an assembly.) There is a .p12 file that I get the private key from.
This is the code I was trying to use, but I get a System.Security.Cryptography.CryptographicException "Invalid algorithm specified.".
X509Certificate pXCert = new X509Cert... | RSA + SHA256 can and will work...
Your later example may not work all the time, it should use the hash algorithm's OID, rather than it's name. As per your first example, this is obtained from a call to CryptoConfig.MapNameToOID(AlgorithmName) where AlgorithmName is what you are providing (i.e. "SHA256").
First you are... | Bouncy Castle | 7,444,586 | 50 |
I was trying to extract RES public key from the file below
-----BEGIN CERTIFICATE-----
MIIGwTCCBamgAwIBAgIQDlV4zznmQiVeF45Ipc0k7DANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSUwIwYDVQQDExxEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBDQS0zMB4XDTEyMTAzMDAwMDAwMFoXDTE1MTEwN... | An X.509 certificate and an X509EncodedKeySpec are quite different structures, and trying to parse a cert as a key won't work.
Java's X509EncodedKeySpec is actually SubjectPublicKeyInfo from X.509 or equivalent and more convenient PKIX also linked from Key, which is only a small part of a certificate.
What you need to ... | Bouncy Castle | 24,137,463 | 49 |
I need to encrypt a stream with pgp using the bouncycastle provider. All of the examples I can find are about taking a plain text file and encrypting that however I won't have a file and it's important that the plain text never be written to disk.
Most of the methods I've seen are using
PGPUtil.writeFileToLiteralData ... | Looking at the source of PGPUtil you can see what API to call when working with streams or arrays directly:
public static void writeFileToLiteralData(OutputStream out,
char fileType, File file, byte[] buffer) throws IOException {
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
Output... | Bouncy Castle | 3,939,447 | 45 |
I'm trying to securely store a password in a database and for that I chose to store its hash generated using the PBKDF2 function. I want to do this using the bouncy castle library but I don't know why I cannot get it to work by using the JCE interface...
The problem is that generating the hash in 3 different modes:
1... | In short, the reason for the difference is that PBKDF2 algorithm in modes #1 and #2 uses PKCS #5 v2 scheme 2 (PKCS5S2) for iterative key generation, but the BouncyCastle provider for "PBEWITHHMACSHA1" in mode #3 uses the PKCS #12 v1 (PKCS12) algorithm instead. These are completely different key-generation algorithms, s... | Bouncy Castle | 8,674,018 | 41 |
We're trying to generate an X509 certificate (including the private key) programmatically using C# and the BouncyCastle library. We've tried using some of the code from this sample by Felix Kollmann but the private key part of the certificate returns null. Code and unit test are as below:
using System;
using System.Col... | Just to clarify, an X.509 certificate does not contain the private key. The word certificate is sometimes misused to represent the combination of the certificate and the private key, but they are two distinct entities. The whole point of using certificates is to send them more or less openly, without sending the privat... | Bouncy Castle | 3,770,233 | 40 |
What is the difference between compute a signature with the following two methods?
Compute a signature with Signature.getInstance("SHA256withRSA")
Compute SHA256 with MessageDigest.getInstance("SHA-256") and compute the digest with Signature.getInstance("RSA"); to get the signature?
If they are different, is there a ... | The difference
The difference between signing with "SHA256withRSA" and computing the SHA256 hash and signing it with "RSA" (= "NONEwithRSA") is foremost that in the former case the calculated SHA-256 hash value is first encapsulated in a DigestInfo structure
DigestInfo ::= SEQUENCE {
digestAlgorithm DigestAlgorithm... | Bouncy Castle | 33,305,800 | 39 |
I cannot find any code/doc describing how to sign a CSR using BC. As input I have a CSR as a byte array and would like to get the cert in PEM and/or DER format.
I have gotten this far
def signCSR(csrData:Array[Byte], ca:CACertificate, caPassword:String) = {
val csr = new PKCS10CertificationRequestHolder(csrData)
va... | Ok ... I was looking to do the same stuff and for the life of me I couldn't figure out how. The APIs all talk about generating the key pairs and then generating the cert but not how to sign a CSR. Somehow, quite by chance - here's what I found.
Since PKCS10 represents the format of the request (of the CSR), you first ... | Bouncy Castle | 7,230,330 | 37 |
I've been looking around for about a week+ to implement a method I have in mind. I have came across (and read) many articles on all of these different methods, but I am still left confused, so I was hoping maybe someone can spread their knowledge of these topics so I can more easily go about creating my sought after me... | It is complicated, but I'll try to explain as best I can. I think I'll start with Java. My discussion is geared to Java 6, I'm not sure what has changed in Java 7.
Java' built-in cryptography is available through the Java Cryptography Extension (JCE). This extension has two parts to it, the application API and servic... | Bouncy Castle | 9,962,825 | 35 |
I am using bcmail-jdk16-1.46.jar and bcprov-jdk16-1.46.jar (Bouncycastle libraries) to sign a string and then verify the signature.
This is my code to sign a string:
package my.package;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java... | The
gen.generate(msg, false)
means the signed data is not encapsulated in the signature. This is fine if you want to create a detached signature, but it does mean that when you go to verify the SignedData you have to use the CMSSignedData constructor that takes a copy of the data as well - in this case the code is usi... | Bouncy Castle | 16,662,408 | 34 |
How can one programmatically obtain a KeyStore from a PEM file containing both a certificate and a private key? I am attempting to provide a client certificate to a server in an HTTPS connection. I have confirmed that the client certificate works if I use openssl and keytool to obtain a jks file, which I load dynamica... | I figured it out. The problem is that the X509Certificate by itself isn't sufficient. I needed to put the private key into the dynamically generated keystore as well. It doesn't seem that BouncyCastle PEMReader can handle a PEM file with both cert and private key all in one go, but it can handle each piece separatel... | Bouncy Castle | 12,501,117 | 30 |
Apparently Spongy Castle is the Android alternative to using a full version of Bouncy Castle.
However, on importing the jar I'm getting all kinds of "cannot be resolved" errors because it relies on packages not included with Android, primarily javax.mail, javax.activation, and javax.awt.datatransfer.
So what's the best... | If you are using gradle, then you can just specify your dependencies in build.gradle file like this:
dependencies {
....
compile 'com.madgag.spongycastle:core:1.54.0.0'
compile 'com.madgag.spongycastle:prov:1.54.0.0'
compile 'com.madgag.spongycastle:pkix:1.54.0.0'
compile 'com.madgag.spongycastle:p... | Bouncy Castle | 6,898,801 | 29 |
I need to encrypt data in C# in order to pass it to Java. The Java code belongs to a 3rd party but I have been given the relevant source, so I decided that as the Java uses the Bouncy Castle libs, I will use the C# port.
Decryption works fine. However, decryption works only when I use the encrypt using the private key,... | There are some errors in OP's code. I made few changes. Here is what I got running.
public class TFRSAEncryption
{
public string RsaEncryptWithPublic(string clearText, string publicKey)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
var encryptEngine = new Pkcs1Encoding(new RsaEngine... | Bouncy Castle | 28,086,321 | 29 |
So after CodingHorror's fun with encryption and the thrashing comments, we are reconsidering doing our own encryption.
In this case, we need to pass some information that identifies a user to a 3rd party service which will then call back to a service on our website with the information plus a hash.
The 2nd service loo... | High level abstraction? I suppose the highest level abstractions in the Bouncy Castle library would include:
The BlockCipher interface (for symmetric ciphers)
The BufferedBlockCipher class
The AsymmetricBlockCipher interface
The BufferedAsymmetricBlockCipher class
The CipherParameters interface (for initializing the b... | Bouncy Castle | 885,485 | 28 |
I'm trying to use bouncycastle to encrypt a file using a public key.
I've registered the provider programatically:
Security.addProvider(new BouncyCastleProvider());
I created the public key object successfully.
when i get to encrypting the file using a PGPEncryptedDataGenerator and the key I get a ClassNotFound except... | You have a BouncyCastle Security provider installation problem, you need to either
Add BouncyCastle to the JRE/JDK $JAVA_HOME/jre/lib/security/java.security file as a provider (be sure that you add it to the JRE you use when running, eg. if you have multiple JRE's/JDK's installed)
eg.
security.provider.2=org.bouncyca... | Bouncy Castle | 6,908,696 | 28 |
UPDATED 2019: Bouncycastle now support PBKDF2-HMAC-SHA256 since bouncycastle 1.60
Is there any reliable implementation of PBKDF2-HMAC-SHA256 for JAVA?
I used to encrypt using bouncycastle but it does not provide PBKDF2WithHmacSHA256'.
I do not want to write crypto module by myself.
Could you recommend any alternative ... | Using BouncyCastle classes directly:
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
gen.init("password".getBytes("UTF-8"), "salt".getBytes(), 4096);
byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
| Bouncy Castle | 22,580,853 | 27 |
I use BouncyCastle for encryption in my application. When I run it standalone, everything works fine. However, if I put it in the webapp and deploy on JBoss server, I get a following error:
javax.servlet.ServletException: error constructing MAC: java.security.NoSuchProviderException: JCE cannot authenticate the provide... | For JBoss AS7 bouncy castle needs to be deployed as a server module. This replaces the server/default/lib mechanism of earlier versions (as mentioned in Gergely Bacso's answer).
JBoss AS7 uses jdk1.6+. When using JBoss AS7 with jdk1.6 we need to make sure we are using bcprov-jdk16.
Create a Jboss module (a folder $JBOS... | Bouncy Castle | 9,534,512 | 26 |
Update: Partial solution available on Git
EDIT: A compiled version of this is available at https://github.com/makerofthings7/Bitcoin-MessageSignerVerifier
Please note that the message to be verified must have Bitcoin Signed Message:\n as a prefix. Source1 Source2
There is something wrong in the C# implementation th... | After referencing BitcoinJ, it appears some of these code samples are missing proper preparation of the message, double-SHA256 hashing, and possible compressed encoding of the recovered public point that is input to the address calculation.
The following code should only need BouncyCastle (probably you'll need recent v... | Bouncy Castle | 19,665,491 | 26 |
Surprisingly enough there's very little information on the Web about using Bouncy Castle's lightweight API. After looking around for a while I was able to put together a basic example:
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(new RSAKeyGenerationParameters
(
new BigInteger("... | You are using correct values for both.
The publicExponent should be a Fermat Number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also.
The RSA key generation requires prime numbers. However, it's impossible to generate absolute prime numbers. Like any other crypto libraries, BC uses probable p... | Bouncy Castle | 3,087,049 | 25 |
I am new to the security side of Java and stumbled across this library called BouncyCastle. But the examples that they provide and the ones out on the internet ask to use
return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(
"CN=Requested Test Certificate"), pair.getPublic(), null, pair.getPriva... | With the recent versions of BouncyCastle it is recommended to create the CSR using the org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder class.
You can use this code snipppet:
KeyPair pair = generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
new X500Pri... | Bouncy Castle | 20,532,912 | 25 |
I'm trying to use iText Java.
When you run the example "how to sign" the following error occurs:
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.tsp.TimeStampTokenInfo
According "Getting Started with iText - How to sign a PDF using iText", I have to use the BouncyCastle.
I downloaded the file: bcprov-jdk... | iText marks bouncycastle dependencies as optional. If you require them, you need to add the dependencies in your own pom file.
To find out which dependency to include in your project, open the itextpdf pom.xml file of the version you are using (for example 5.3.2, here) and search for the 2 bouncycastle dependencies.
... | Bouncy Castle | 10,391,271 | 23 |
I've seen a number of posts, followed a number of tutorials but none seems to work. Sometimes, they make reference to some classes which are not found. Can I be pointed to a place where I can get a simple tutorial showing how to encrypt and decrypt a file.
I'm very new to Pgp and any assistance is welcomed.
| I know this question is years old but it is still #1 or #2 in Google for searches related to PGP Decryption using Bouncy Castle. Since it seems hard to find a complete, succinct example I wanted to share my working solution here for decrypting a PGP file. This is simply a modified version of the Bouncy Castle example ... | Bouncy Castle | 6,987,699 | 22 |
I'm creating a certificate distribution system to keep track of clients and stuff.
What happens is:
Client send CSR to Server
Server checks and signs certificate
Server sends Signed certificate to Client
Client puts Signed certificate plus Private key in Windows store.
So on the client this happens:
//Pseudo Server O... | The answer (from username) points to the right direction: padding.
Bouncy-castle's latest version from git has the following code:
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exp... | Bouncy Castle | 949,727 | 20 |
I'm having problems inserting a new CA certificate with privatekey in the Root certificate store of the localmachine.
This is what happens:
//This doesn't help either.
new StorePermission (PermissionState.Unrestricted) { Flags = StorePermissionFlags.AddToStore }.Assert();
var store = new X509Store(StoreName.Root, Stor... | I had exactly the same problem and the solution turned out to be really simple.
All I had to do is to pass
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
to X509Certificate2's ctor.
Now you are using the DotNetUtilities to convert the bouncycastle certificate to the .net one, but the helper met... | Bouncy Castle | 3,625,624 | 20 |
I am using the "BouncyCastle.Crypto.dll" for encrypt/decrypt a string in my app. I am using the
following code from this blog:
I have a class BCEngine, exactly the same as the one given in the link mentioned above.
public class BCEngine
{
private readonly Encoding _encoding;
private readonly IBlockCipher _blockC... | Your string key = "DFGFRT"; is not 128/192/256 bits.
DFGFRT is 6 characters, which is 6 (or 12?) bytes = 8*12 = 96 bits (at most).
To get a 128 bit key you need a 16 byte string, so I'd go on the safe side and use a 16 character string so it will be a 128 bit key if using single byte characters and 256 if using wide ... | Bouncy Castle | 5,910,454 | 20 |
Can you help me to find a simple tutorial of how sign a string using ECDSA algorithm in java. But without using any third-party libraries like bouncycastle. Just JDK 7. I found it difficult to search a simple example, I'm new to cryptography.
import java.io.*;
import java.security.*;
public class GenSig {
/**
... | Here is small example based on your example.
NOTE: this is the original code for this answer, please see the next code snippet for an updated version.
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import... | Bouncy Castle | 11,339,788 | 20 |
In my build process, I want to include a timestamp from an RFC-3161-compliant TSA. At run time, the code will verify this timestamp, preferably without the assistance of a third-party library. (This is a .NET application, so I have standard hash and asymmetric cryptography functionality readily at my disposal.)
RFC 3... | I finally figured it out myself. It should come as no surprise, but the answer is nauseatingly complex and indirect.
The missing pieces to the puzzle were in RFC 5652. I didn't really understand the TimeStampResp structure until I read (well, skimmed through) that document.
Let me describe in brief the TimeStampReq a... | Bouncy Castle | 19,528,456 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.