I'm using this task to add a line to a file:
lineinfile: "dest={{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb
insertbefore='# role-based syntax'
line='server "'{{ ip_addr }}'", user: "'{{ user_name }}'", roles: %w{'{{ role }}'}'"
Which adds this line:
server '172.16.8.11', user: 'vagrant', roles: %w{'api'}
But I don't want the quotes around api. Instead I want this output:
server '172.16.8.11', user: 'vagrant', roles: %w{api}
Actually the quotes do not come from the variable, but are right there in your string:
%w{'{{ role }}'}
Now the solution is little bit tricky though. Because you can not simply remove the quotes like that:
%w{{{ role }}}
This would result into a parse error, since {{ starts an expression...
The solution is to write the outer parentheses, which are meant to be in the string, as an expression themselves.
So to output { you would instead write {{'{'}} and instead of } you would write {{'}'}}. Does that make sense? You're instructing the template engine (Jinja2) to output the parentheses to avoid the parsing error:
%w{{'{'}}{{ role }}{{'}'}}
But since role is an expression already, you just also can group it together into one single expression:
%w{{ '{'+role+'}' }}
Your whole task would then read like this:
- lineinfile:
dest: "{{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb"
insertbefore: "# role-based syntax"
line: "server '{{ ip_addr }}', user: '{{ user_name }}', roles: %w{{ '{'+role+'}' }}"
This also is converted into proper YAML syntax because this quoted k=v format is just really hard to read. :)
Related
I'm customizing linux users creation inside my role. I need to let users of my role customize home_directory, group_name, name, password.
I was wondering if there's a more flexible way to cope with default values.
I know that the code below is possible:
- name: Create default
user:
name: "default_name"
when: my_variable is not defined
- name: Create custom
user:
name: "{{my_variable}}"
when: my_variable is defined
But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities.
Is there something like the code above?
user:
name: "default_name", "{{my_variable}}"
The code should set name="default_name" when my_variable isn't defined.
I could set all variables on defaults/main.yml and create the user like that:
- name: Create user
user:
name: "{{my_variable}}"
But those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.
You can use Jinja's default:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
Not totally related, but you can also check for both undefined AND empty (for e.g my_variable:) variable. (NOTE: only works with ansible version > 1.9, see: link)
- name: Create user
user:
name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
if my_variable is defined else 'default_value' }}"
If anybody is looking for an option which handles nested variables, there are several such options in this github issue.
In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"
or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.
In case you using lookup to set default read from environment you have also set the second parameter of default to true:
- set_facts:
ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"
You can also concatenate multiple default definitions:
- set_facts:
ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"
If you are assigning default value for boolean fact then ensure that no quotes is used inside default().
- name: create bool default
set_fact:
name: "{{ my_bool | default(true) }}"
For other variables used the same method given in verified answer.
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:
all_items:
- first
- second
- third
- fourth
Then your task can look like this:
- name: List items or default list
debug:
var: item
with_items: "{{ varlist | default(all_items) }}"
Pass in varlist as a JSON array:
ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'
Prior to that, you might also want a task that checks that each item in varlist is also in all_items:
- name: Ensure passed variables are in all_items
fail:
msg: "{{ item }} not in all_items list"
when: item not in all_items
with_items: "{{ varlist | default(all_items) }}"
The question is quite old, but what about:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"
It looks less cumbersome to me...
#Roman Kruglov mentioned json_query. It's perfect for nested queries.
An example of json_query sample playbook for existing and non-existing value:
- hosts: localhost
gather_facts: False
vars:
level1:
level2:
level3:
level4: "LEVEL4"
tasks:
- name: Print on existing level4
debug:
var: level1 | json_query('level2.level3.level4') # prints 'LEVEL4'
when: level1 | json_query('level2.level3.level4')
- name: Skip on inexistent level5
debug:
var: level1 | json_query('level2.level3.level4.level5') # skipped
when: level1 | json_query('level2.level3.level4.level5')
I'm trying to use a var in a var declaration on Ansible (2.7.10)
I'm using aws_ssm lookup plugin (https://docs.ansible.com/ansible/latest/plugins/lookup/aws_ssm.html)
Working example (hardcoded values):
var: "{{ lookup('aws_ssm', '/path/server00', region='eu-west-3') }}"
I want to use variables for the server name and the AWS region, but all my tentatives went on errors.
What I've tried so far:
var: "{{ lookup('aws_ssm', '/path/{{ server }}', region={{ region }}) }}"
var: "{{ lookup('aws_ssm', '/path/{{ server }}', region= + region) }}"
- name: xxx
debug: msg="{{ lookup('aws_ssm', '/path/{{ server }}', region='{{ region }}' ) }}"
register: var
Without any success yet, thanks for your help,
You never nest {{...}} template expressions. If you're already inside a template expression, you can just refer to variables by name. For example:
var: "{{ lookup('aws_ssm', '/path/' + server, region=region) }}"
(This assumes that the variables server and region are defined.)
You can also take advantage of Python string formatting syntax. The following will all give you the same result:
'/path/' + server
'/path/%s' % (server)
'/path/{}'.format(server)
And instead of + you can use the Jinja ~ concatenation operator, which acts sort of like + but forces arguments to be strings. So while this is an error:
'some string' + 1
This will result in the text some string1:
'some string' ~ 1
I am trying to use wildcard for my ansible variable but it seems like i cant manage to use it.
I have tried something from here but still the same.
the ansible output
"reboot_required": false,
"updates": {
"0720a128-90b1-4b21-a8cf-3c5c86239435": {
"kb": [
"2267602"
],
"installed": false,
"id": "0720a128-90b1-4b21-a8cf-3c5c86239435",
"categories": [
"Definition Updates",
"Windows Defender"
],
"title": "Definition Update for Windows Defender Antivirus - KB2267602 (Definition 1.297.412.0)"
},
"60bbf4af-afd3-45fe-aad2-6d72beddeba2": {
"kb": [
"4509475"
],
"installed": false,
"id": "60bbf4af-afd3-45fe-aad2-6d72beddeba2",
"categories": [
"Updates",
"Windows Server 2016"
],
"title": "2019-06 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4509475)"
I am trying to get the title, or id
- name: debug
debug:
msg: "{{ item.updates.*.id }}"
with_items:
- "{{ result }}"
appreciate the help
Given the ansible output above is stored in the variable result the tasks below
- set_fact:
id_list: "{{ result.updates|
json_query('*.id')
}}"
- debug:
var: id_list
give the list of id (similar titles)
id_list:
- 0720a128-90b1-4b21-a8cf-3c5c86239435
- 60bbf4af-afd3-45fe-aad2-6d72beddeba2
And the tasks below
- set_fact:
my_list: "{{ result.updates|
json_query('*.{ id: id, title: title }')
}}"
- debug:
var: my_list
give the list of the id, title hashes
my_list:
- id: 0720a128-90b1-4b21-a8cf-3c5c86239435
title: Definition Update for Windows Defender Antivirus - KB2267602 (Definition 1.297.412.0)
- id: 60bbf4af-afd3-45fe-aad2-6d72beddeba2
title: 2019-06 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4509475)
The wildcard he's using in the example that you linked is apart of the json_query filter. He's piping to the json_query filter and then using the wildcard as part of that syntax.
results | json_query('[].block_device_mapping.*.snapshot_id')
You're not using json_query in your example and therefore, this syntax is not available and won't work.
Try piping your results to json_query and then including the path that you want to get to. If {{ results }} is already created you can leave off the with_items and go with something like:
{{ results | json_query('updates.*.id') }}
I'm guessing here at the exact syntax but you definitely have to start with json_query.
To figure out the exact syntax you want, start small piping to json_query and then grabbing the top most element(updates, in your case), adding pieces to the filter until you've narrowed it down to the information you want. I've linked to a pathfinder below that helps.
Reference:
json_query filter documentation
json_query documentation
jsonpath finder to help you figure stuff out easier.
edit: The syntax in the first part of the answer from Vladimir looks way sexier than what I'm guessing at. Try his syntax to get to what works, use my answer to understand what's wrong. Then mark him as the correct answer.
Try below. I have not tested it though.
- name: debug
debug:
msg: "{{ item|first }}:{{ item[item|first].title }}"
with_items:
- "{{ result.updates }}"
I want to create new user and then copy SSH key to this users dir (I've got this key before executing role). After that I'd like to disable password login.
Here's what I've got for now:
My tasks/main.yml
- name: Add users
user: name={{ item }}
groups=users,wheel
update_password=on_create
password=$6$QoFz/cLhsroToP$4...
with_items:"{{ list }}"
- name: Copy SSH keys
authorized_key: user={{ item }} key={{ item }}.pub state=present
with_items: "{{ list }}"
My vars/main.yml file:
list:
- 'user1'
- 'user2'
- 'user3'
And here's my question - where are my keys stored? Is that form of copying correct?
I've got an error:
failed: [127.0.0.1] => (item=user1) => {"failed": true, "item": "user1"}
msg: invalid key specified: user1.pub
The second task will fail as authorized_key expects the key parameter to be a string ( authorized_key docs ). You can still use the list parameter to get the content of the key file, but you will have to use a lookup.
So this is what the second task might look like:
- name: "Copy SSH Keys"
authorized_key: user={{ item }} key={{ lookup('file', item) }} state=present
To answer your question "Where would the file be stored, that's entirely up to you. By default ( If you don't specify a path ) the module will look into all the files/ directories available. So if it's a role it will look into:
/roles/your_role/files
/files
./files
Lookups docs
Thanks for answer, i could'nt comment your post, beacuse my answer would be too long.
I can finally see keys from ansible side, but the task still fails. Here's the output:
failed: [127.0.0.1] => (item=user1) => {"failed": true, "item": "user1"}
msg: this module requires key=value arguments (['user=user1', 'key=ssh-rsa', 'AAAAB3NzaC1yc2EAAAADAQABAAA...', 'user#domain', 'state=present'])
Am I doing something wrong?
FOUND THE ANSWER!
Quoting the key inputs solves the problem, so the function in my case should look like this:
- name: "Copy SSH Keys"
authorized_key: user="{{ item }}" key="{{ lookup('file', item) }}" state=present
Hope it will help someone in the future. Thanks a lot for help!
Let's suppose i have some applications inside a repository. Sensitive data, like database username+password, are not stored inside the repository but are in a separate encrypted password database. Within the source code are only place-holders like this: %%mysqlpassword%%.
I want to create an ansible-playbook to checkout the code and replace the user-credentials.
I have two ideas to do so:
with a template or
with the replace module.
Is there a best practise way to accomplish this task?
---
- hosts: test
vars_prompt:
- name: "mysqlpassword"
prompt: "Enter mysql password for app"
private: yes
tasks:
- name: copy code from repo
subversion: repo=https://repo.url.local/app dest=/srv/www/app
- name: Replacement of sensitive data by templating
template: src=mysqlconnect.php.j2 dest=/srv/www/app/inc/mysqlconnect.php
- name: Replacement of sensitive data by replacement function
replace: dest=/srv/www/app/inc/mysqlconnect.php regexp='%%mysqlpassword%%' replace='{{ mysqlpassword }}'
The best answer to your question is use ansible-vault.
1- use mysqlpassword as variable {{ mysqlpassword }} inside your template mysqlconnect.php.j2
2- create separate file like my_very_secure.yml(whatever name you want) with all the values of your secure username and password:
---
mysqlpassword: very-secure-password-value
anothervariable: another-secure-value
After that you can encrypt this file with ansible-vault:
ansible-vault encrypt my_very_secure.yml
Then you can store this file into source control server because it's encrypted or leave it on the ansible master server, but once you are ready to run the playbook just include the --ask-vault-pass option like this and path to your secure file:
ansible-playbook -i yourhostfile yourplaybook.yml -e#/path-to-your-file/my_very_secure.yml --ask-vault-pass
Hope this will help you.