Ansible if nested value doesn't exist in nested array - ansible-facts

I'd like to make my Ansible EIP creation idempotent. In order to do that I only want the task to run when Tag "Name" value "tag_1" doesn't exist.
However I'm not sure how I could add this as a 'when' at the end of a task.
"eip_facts.addresses": [
{
"allocation_id": "eipalloc-blablah1",
"domain": "vpc",
"public_ip": "11.11.11.11",
"tags": {
"Name": "tag_1",
}
},
{
"allocation_id": "eipalloc-blablah2",
"domain": "vpc",
"public_ip": "22.22.22.22",
"tags": {
"Name": "tag_2",
}
},
{
"allocation_id": "eipalloc-blablah3",
"domain": "vpc",
"public_ip": "33.33.33.33",
"tags": {
"Name": "tag_3",
}
}
]
(Tags are added later) I'm looking for something like:
- name: create elastic ip
ec2_eip:
region: eu-west-1
in_vpc: yes
when: eip_facts.addresses[].tags.Name = "tag_1" is not defined
What is the correct method of achieving this? Bear in mind the value can not exist in that parameter in the entire array, not just a single iteration.

Ok, I found a semi-decent solution
- name: Get list of EIP Name Tags
set_fact:
eip_facts_Name_tag: "{{ eip_facts.addresses | map(attribute='tags.Name') | list }}"
Which extracts the Name tag and puts them into an array
ok: [localhost] => {
"msg": [
"tag_1",
"tag_2",
"tag_3"
]
}
and then...
- debug:
msg: "Hello"
when: '"tag_1" in "{{ eip_facts_Name_tag }}"'
This will work, beware though, this doesn't do an exact string search. So if you did a search for just 'tag' that'd count as a hit too.

Related

Define a condition in cloudformation template with alarms

How to define/declare a condition to create an alarm in prod?
With the condition:Isprod would work to create an alarm in prod?
WOULD this work? how to define a condition below?
LambdaInvocationsAlarm:
Condition: IsProd
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Lambda invocations
AlarmName: LambdaInvocationsAlarm
ComparisonOperator: LessThanLowerOrGreaterThanUpperThreshold
EvaluationPeriods: 1
Metrics:
- Expression: ANOMALY_DETECTION_BAND(m1, 2)
Id: ad1
- Id: m1
MetricStat:
Metric:
MetricName: Invocations
Namespace: AWS/Lambda
Period: !!int 86400
Stat: Sum
ThresholdMetricId: ad1
TreatMissingData: breaching
As #Marcin said, you should explain what you have tried and what is blocking more precisely.
But what you suggest could work yes: you can define a Condition named isProd and use it to create - or not - resources. Regarding this condition: AWS does not know what is a production stage in your environment, so you need to specify that. Does your production stage matches an account? Does it match a region? Something else?
As an example and if we assume that your production stage matches a specific AWS account, then you could define the condition as below (it's JSON, feel free to convert to YAML):
{
"Parameters": {
"ProdAccountParameter": {
"Type": "String",
"Description": "Enter the production account identifier."
}
},
"Conditions": {
"isProd": {
"Fn::Equals": [
{
"Ref": "ProdAccountParameter"
},
{
"Ref": "AWS::AccountId"
}
]
}
},
...
}
(Then, when deploying the template, you'll need to provide your AWS production account).

Accessing values of nested dictionaries

I'm working some separate tasks for automating VM deployments through tower.
Basically I just need a quick run down on how to gather/use the various properties of a registered return from a task.
I've got this.
tasks:
- name: Gather disk info from virtual machine using name
vmware_guest_disk_info:
hostname: "{{ vcenter }}"
username: "{{ username }}"
password: "{{ esxipassword }}"
datacenter: "{{ datacenter }}"
name: "{{ fqdn }}"
register: disk_info
- debug:
var: disk_info
This spits out the information I want. But, for the life of me I can't figure out how to select a single property. can someone tell me how to do that (particularly for the backing_filename) property?
I mean in powershell it would just be disk_info.backing_filename or something like backing = $disk_info | select -expandproperty backing_filename. Just looking for something like the equivalent of that.
Snip of output
{
"disk_info": {
"guest_disk_info": {
"0": {
"key": 2000,
"label": "Hard disk 1",
"summary": "104,857,600 KB",
"backing_filename": "[datastorex] vmname/vmname.vmdk",
To be fair, this one is not as simple as it looks, because your dictionary has a key being a string 0, but, would you be doing disk_info.guest_disk_info.0.backing_filename you would try to access an element 0, so a list, and not a dictionary key '0'.
Here would be an example playbook solving your issue:
- hosts: all
gather_facts: yes
tasks:
- debug:
var: disk_info.guest_disk_info['0'].backing_filename
vars:
disk_info:
guest_disk_info:
'0':
key: 2000
label: Hard disk 1
summary: 104,857,600 KB
backing_filename: "[datastorex] vmname/vmname.vmdk"
That gives:
{
"disk_info.guest_disk_info['0'].backing_filename": "[datastorex] vmname/vmname.vmdk"
}
While this works also, you would see that the YAML is representing a totally different structure, also including a list, and not only multiple nested dictionaries:
- hosts: all
gather_facts: yes
tasks:
- debug:
var: disk_info.guest_disk_info.0.backing_filename
vars:
disk_info:
guest_disk_info:
- key: 2000
label: Hard disk 1
summary: 104,857,600 KB
backing_filename: "[datastorex] vmname/vmname.vmdk"
To give you an equivalent in JSON, since you seems to have issue understanding the YAML constructions, your output is
{
"disk_info": {
"guest_disk_info": {
"0": {
"backing_filename": "[datastorex] vmname/vmname.vmdk"
}
}
}
}
That would be accessible via disk_info.guest_disk_info['0'].backing_filename.
While
{
"disk_info": {
"guest_disk_info": [
{
"backing_filename": "[datastorex] vmname/vmname.vmdk"
}
]
}
}
Would be accessible via disk_info.guest_disk_info.0.backing_filename

Ansible cisco ios, shutdown interfaces that are not connected

So here is my current playbook
---
- hosts: SWITCHES
gather_facts: no
tasks:
- name: Show Interface Status
ios_command:
commands:
- show int status
register: out
- debug: var=out.stdout_lines
I basically want to take this script, and then disable all the ports in the "notconnect" state, meaning all the ports with nothing connected to them. Is there a way I can add a "when" statement to this, so that when "show interface status" comes back, it looks at all the ports that are not connected and disables them by applying the "shutdown" command to each interface? I think a "when" statement is what I am needing to do, but not sure where to get started with it. Or is there a better way to accomplish this?
Is there a python script that could accomplish this as well?
You should use ios_facts to retrieve a dictionary containing all the interfaces. Then you can iterate over that dictionary to shutdown the interfaces that are not connected.
If you run your playbook using the -vvv switch, you will see the all the variables collected by ios_facts.
I believe in Ansible 2.9 and later, Ansible gathers the actual network device facts if you specify "gather_facts: yes". With Ansible 2.8 or older, you need to use the "ios_facts" module.
---
- hosts: SWITCHES
gather_facts: no
tasks:
- name: gather IOS facts
ios_facts:
- name: Shutdown notconnect interfaces
ios_config:
lines: shutdown
parents: "interface {{ item.key }}"
with_dict: "{{ ansible_net_interfaces }}"
when: item.value.operstatus == "down"
Here is an example from part of a collected "ansible_net_interfaces" variable:
{
"ansible_net_interfaces": {
"GigabitEthernet0/0": {
"bandwidth": 1000000,
"description": null,
"duplex": "Full",
"ipv4": [],
"lineprotocol": "down",
"macaddress": "10b3.d507.5880",
"mediatype": "RJ45",
"mtu": 1500,
"operstatus": "administratively down",
"type": "RP management port"
},
"GigabitEthernet1/0/1": {
"bandwidth": 1000000,
"description": null,
"duplex": null,
"ipv4": [],
"lineprotocol": null,
"macaddress": "10b3.d507.5881",
"mediatype": "10/100/1000BaseTX",
"mtu": 1500,
"operstatus": "down",
"type": "Gigabit Ethernet"
},
"GigabitEthernet1/0/10": {
"bandwidth": 1000000,
"description": "Telefon/PC",
"duplex": null,
"ipv4": [],
"lineprotocol": null,
"macaddress": "null,
"mediatype": "10/100/1000BaseTX",
"mtu": 1500,
"operstatus": "down",
"type": "Gigabit Ethernet"
},
"GigabitEthernet1/0/11": {
"bandwidth": 1000000,
"description": null,
"duplex": null,
"ipv4": [],
"lineprotocol": null,
"macaddress": "10b3.d507.588b",
"mediatype": "10/100/1000BaseTX",
"mtu": 1500,
"operstatus": "down",
"type": "Gigabit Ethernet"
}
}
The value of the "ansible_net_interfaces" variable is a dictionary. Each key in that dictionary is the interface name, and the value is a new dictionary containing new key/value pairs. The "operstatus" key will have a value "down" when the interface is not connected.
Using "with_dict" in the "ios_config" task loops through all top-level key/value pairs in the dictionary, and you can use the variables in each key/value pair by referring to "{{ item.key }}" or "{{ item.value }}".
Using "when" in the "ios_config" task, you set a condition for when the task is to be executed. In this case we only want it to run when "operstatus" has a value of "down".
The "parents" parameter in the "ios_config" task specifies a new section where the configuration is to be entered, in this case the section is the interface configuration mode. The interface name is returned for each interface in the "ansible_net_interfaces" using the "{{ item.key }}" variable.
Refer to Ansibles documentation for these modules to get a better understanding of them:
https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_facts_module.html
https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_config_module.html

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

Enable Full Text Search in Apache CouchDB

I have followed the blog entry here to enable full text search https://developer.ibm.com/dwblog/2015/text-search-apache-couchdb/#.Vly24SCrQbV
I have everything correctly set up, and have also tried with other peoples docker images.
How do you set up a search? What documents are needed.
I have created a database called cats with one document
{
"_id": "6f35d75b476517e2fc0b3eb12c000e72",
"_rev": "1-c9a6b4734c83287499e8bbd6d1339050",
"name": "tibbles"
}
And a design/view
{
"_id": "_design/cat_look",
"_rev": "1-aae457e6edf5e4a3f69357e5a2160fcc",
"views": {
"kitty_name": {
"map": "function (doc) {\n index(\"kittyName\", doc.name, {\"store\": true});\n}"
}
},
"language": "javascript"
}
If I go to http://localhost:15984/cats/_design/cat_look/_search/kitty_name?q="*"
I get
{"error":"not_found","reason":"kitty_name not found."}
Thanks for any help on this, I am very lost.
A Lucene search index is set up differently to how a Map Reduce view is done. In your code, it looks like you've tried to use a Map Reduce view. For Lucene, first you need to set up an index:
{
"_id": "_design/Cat_look",
"indexes": {
"kitty_name": {
"index": "function(doc){ ... }"
}
}
}
Consult Cloudant's docs on the subject: https://console.bluemix.net/docs/services/Cloudant/api/search.html#search
Thanks for your help, you are right I set up the Lucene search index incorrectly. Here is the code to get a simple example working for anyone else lost.
If you have docker setup
docker run -d -p 15984:15984 ncheaz/couchdb:search
to get couchdb search on local port 15984
The document to search
{
"_id": "6f35d75b476517e2fc0b3eb12c000e72",
"_rev": "1-c9a6b4734c83287499e8bbd6d1339050",
"name": "tibbles"
}
The Search Index.
Create a new document, not a new view.
{
"_id": "_design/cat_look",
"_rev": "2-23f6ab0606a603cbef04653d167585d4",
"views": {},
"language": "javascript",
"indexes": {
"kitty_name": {
"analyzer": "simple",
"index": "function (doc) {if (doc.name) {index(\"name\", doc.name, {\"store\":true}); }}"
}
}
}
The url to search for the cats name is
http://localhost:15984/cats/_design/cat_look/_search/kitty_name?q=name:tibbl*
note that kitty_name is the name of the _search and name is the index name.
I recommend anyone struggling to get this working to create a free trial account on IBM Cloudant as the documentation directly relates to their product and it is a lot easier to follow.