Ansible replace a string in a variable with a variable - variables

debug:
msg: "{{backup_facts | replace(',world',',{{custom}}')}}"
register: replace_csv
in the above code, I am trying to replace a string/word in a variable with a variable.
so in this case these are the vars:
backup_facts = "hello,world"
custom = "prab"
so the end results I would like is: "hello, prab" after the replace. But everytime I run the playbook, I get the following:
"replace_csv": {
"changed": false,
"failed": false,
"msg": "hello,{{custom}}"
}
I have attempted different variation such as putting a quotation around the curly brackets or not putting the curly brackets at all but no results.

Q: "The result is: hello,prab after the replace."
Keep it simple. Put the parameters into variables. This will simplify the code. For example,
- hosts: localhost
vars:
backup_facts: "hello,world"
custom: "prab"
tasks:
- debug:
msg: "{{ backup_facts|replace(old, new) }}"
vars:
old: ",world"
new: ",{{ custom }}"
gives (abridged)
ok: [localhost] =>
msg: hello,prab

Related

Ansible loop with multiple register value

would you please help me with this problem:
I have a playbook with multiple tasks and each tasks contains loop and register for the output of the task. Last task is going to use lineinfile to create a csv report based on the previous registers. something like below:
- name: information
module:
xxxx: xxxx
xxxx: xxxxx
loop:
- xxxx
- xxxx
register: task1_info
- name: information
module:
xxxx: xxxx
xxxx: xxxxx
loop:
- xxxx
- xxxx
register: task2_info
- name: information
lineinfile:
path: xxxx
line: "{{ item.tags.Name }}, {{ item.lastName }}"
loop:
- task1_info.results
- task2_info.results
if i use only one register at the end it is working, but not loop through all registers. the other option is to write a task after each register which I don't think reasonable!!
I understand your use case that you like to append one list to an other or to merge two lists.
To do so you could use an approach like
---
- hosts: localhost
become: false
gather_facts: false
vars:
LIST_1:
- 1
- 2
- 3
LIST_2:
- A
- B
- C
tasks:
- name: Info
debug:
msg: "{{ item }}"
loop: "{{ LIST_1 + LIST_2 }}"
loop_control:
extended: true
label: "{{ansible_loop.index0 }}"
resulting into an output of
TASK [Info] ******************
ok: [localhost] => (item=0) =>
msg: 1
ok: [localhost] => (item=1) =>
msg: 2
ok: [localhost] => (item=2) =>
msg: 3
ok: [localhost] => (item=3) =>
msg: A
ok: [localhost] => (item=4) =>
msg: B
ok: [localhost] => (item=5) =>
msg: C
Credits to
Append list variable to another list in Ansible
Further Q&A
Combine two lists in Ansible when one list could be empty
Ansible: Merge two lists based on an attribute

Remove first line in 'stdout_lines'

I'm just a beginner and write some small playbook.
For now I get some little error.
- name: Facts
ios_command:
commands: show interface status
register: ios_comm_result
In this playbook, for beginner I get the list of interfaces and then in next task I get list with first position including column name.
- name: get a list of ports to modify
set_fact:
newlist: "{{ (newlist | default([])) + [item.split()[0]] }}"
with_items: "{{ ios_comm_result.stdout_lines }}"
Output:
'Port'
'fa0/1'
'gi0/2'
....
etc
How can I delete first line? Or where can I read about this?
Based on your requirement and the given comments about Accessing list elements with Slice notation ([1:]) and Jinja Filters (| reject()) I've setup an short test
---
- hosts: localhost
become: false
gather_facts: false
vars:
STDOUT_LINES: ['Port', 'fa0/1', 'gi0/2', 'etc/3']
tasks:
# Slice notation
- name: Show 'stdout_lines' from the 2nd line to the end
debug:
msg: "{{ item }}"
loop: "{{ STDOUT_LINES[1:] }}"
# Jinja2 filter
- name: Show 'stdout_lines' and drop any lines which match
debug:
msg: "{{ item }}"
loop: "{{ STDOUT_LINES | reject('match', '^Port') | list }}"
# Conditionals
- name: Show 'stdout_lines' but not the first one
debug:
msg: "{{ item }}"
when: ansible_loop.index != 1
loop: "{{ STDOUT_LINES }}"
loop_control:
extended: true
label: "{{ ansible_loop.index0 }}"
with some value added about Extended loop variables and using conditionals in loops.
All three options show the expected result.

Ansible debug module print undesired details [duplicate]

I'm trying to get a debug message from the results of a previous loop, but I can't get just the bit that I want from it. Ansible keeps giving me the entire result instead just the line I'm asking for.
Here are the 2 modules I'm using:
- name: Make the curl call
uri:
url: https://www.theurl.com
method: GET
return_content: yes
headers:
XXXX: "xxxxxxxxxx"
loop: "{{ simplelist }}"
register: this
- name: just testing
debug:
msg: "I just want to see: {{ item.json.section.test }}"
loop: "{{ this.results}}"
As you can see from the msg, I'm just trying to output that specific value, but what Ansible gives me is:
{
"ansible_loop_var": "item",
"_ansible_no_log": false,
"item": {
"content_length": "",
"cookies": {},
"via": "1.1 varnish",
"connection": "",
"vary": "Accept-Encoding",
"x_timer": "",
"access_control_allow_methods": "OPTIONS, HEAD, GET, PATCH, DELETE",
"x_cache_hits": "0",
"failed": false,
"access_control_allow_credentials": "true",
"content": blah blah blah,
"json": { the json },
"changed": false,
"msg": "I just want to see: False",
So it is setting the message, as you can see from the last line, and it is getting the correct value, but it's not outputting that message. How can I get just the message to be output? I tested and I know that I can get the value because the msg has False and I tested with doing a fail/when with that value.
What you are seeing looks like a verbose output of ansible-playbook running with the -v[vv] option. You can drop that option to decrease verbosity.
Meanwhile, even in non-verbose mode, and whatever module your are using, when going over a loop, ansible outputs a label for each iteration, roughly looking like the following (watch for the (item=....) part of the screen).
TASK [test] *******************************************************************************
ok: [localhost] => (item={'a': 1, 'b': 2}) => {
"msg": "This is the value of a: 1"
}
ok: [localhost] => (item={'a': 3, 'b': 4}) => {
"msg": "This is the value of a: 3"
}
By default, the label is a the full item your are currently looping over. But you can change this label in the loop_control parameter which can be a little too verbose for complex data structures. If you really want an empty label your can use the following example. But you will still get ok: [server1] => (item=) => prepended to each iteration output.
- name: just testing
debug:
msg: "I just want to see: {{ item.json.section.test }}"
loop: "{{ this.results }}"
loop_control:
label: ""
For more info see limiting loop output with label

Saving a random choice string to a usable variable in ansible

Hoping someone can help me figure out what I feel should be a simple nested string problem. I have the following tasks to randomly choose a string, save it to a variable and print it:
tasks:
- name: Debug Section 1
debug:
msg: "{{ item }}"
with_random_choice:
- MY_CHOICE1
- MY_CHOICE2
register: choice
- name: Set result to a fact
set_fact:
THE_CHOICE: "{{ choice.results }}"
- name: Debug Section 3
debug:
msg: "{{ THE_CHOICE }}"
The results return with:
PLAY [Testing variable] **********************************************************************************************************************************************************************************************************************
TASK [Debug Section 1] ***********************************************************************************************************************************************************************************************************************ok: [localhost] => (item=MY_CHOICE1) => {
"msg": "MY_CHOICE1"
}
TASK [Set result to a fact] ******************************************************************************************************************************************************************************************************************ok: [localhost]
TASK [Debug Section 3] ***********************************************************************************************************************************************************************************************************************ok: [localhost] => {
"msg": [
{
"ansible_loop_var": "item",
"changed": false,
"failed": false,
"item": "MY_CHOICE1",
"msg": "MY_CHOICE1"
}
]
}
PLAY RECAP ***********************************************************************************************************************************************************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
I would like the variable THE_CHOICE to just return the item, but I can't seem to get it to work. In the set_fact section I've tried the following:
THE_CHOICE: "{{ choice.results['item'] }}"
THE_CHOICE: "{{ choice.results.item }}"
THE_CHOICE: "{{ choice['results']['item'] }}"
All attempts result in something to the effect of this:
"The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'item'
Could anybody provide some insight into what I'm missing?
It would be simpler to use the random filter (since Ansible 1.6):
vars:
choices:
- MY_CHOICE1
- MY_CHOICE2
tasks:
- name: Set fact random
set_fact:
THE_CHOICE: "{{ choices | random }}"
About your original playbook, choice.results is a list, containing one result for each item of the loop. In your case, it only contains one result, because the with_random_choice loop only iterates once. So, in order to access your item, you must select the first result of the list with [0]:
- name: Set result to a fact
set_fact:
THE_CHOICE: "{{ choice.results[0].item }}"

Using extra-var to call a defined variable in ansible

Is this possible? I have a playbook looking like this:
vars:
BDNAME: ""
- name: Add a tenant using a JSON string
aci_bd:
tenant: "common"
bd: "{{ BDNAME }}"
vrf: "PIGGE"
hostname: '1.1.1.1'
username: "x"
password: "x"
use_ssl: yes
validate_certs: false
It works if i provide an extra variable in the commandline:
ansible-playbook apic.yml -i server.yml --extra-vars BDNAME='pooh'
Then BDNAME gets the value pooh.
But is there any way that i can define pooh as a variable. So if i run the playbook like i just did, BDNAME get the value of that variable.
So something like
vars:
BDNAME: ""
POOH: nisse
Then BDNAME should be nisse.
Define BDNAME in playbook directly from the extra variable POOH. That should do what you want. But it would be easier to use POOH instead of BDNAME.
Here is a example playbook:
---
- hosts: localhost
vars:
BDNAME: "{{ POOH }}"
tasks:
- name: print BDNAME
debug:
msg: "{{ BDNAME }}"
if you call it with:
ansible-playbook playbook.yml -e '{"POOH": "Oliver"}'
you will see:
TASK [print BDNAME] **********************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"changed": false,
"msg": "Oliver"
}