Day 93: A Condition That Can Skip Everything and a Flag That Rewrites What It Names
DEV Community

Day 93: A Condition That Can Skip Everything and a Flag That Rewrites What It Names

Day 93 of DevOps, Day 43 of Azure. Both tasks produced a wrong answer that looked like a right one.

The Ansible playbook has a failure mode where every task skips and the recap says success. The Azure task gave me an empty array in the middle of a diagnosis, and it read as a finding.

One Ansible task, one Azure task. Conditionals that route files to hosts, then an Application Gateway the CLI could not build. The tasks come from the KodeKloud Engineer platform.

Task 1: Copying a different file to each server with conditionals

Three app servers, three files, each going to exactly one server. Owned by the connecting user, mode 0655.

Step 1: The playbook

- hosts: all
  become: yes
  tasks:
    - name: Copy blog.txt file from jump host to App Server 1
      copy:
        src: /usr/src/dba/blog.txt
        dest: /opt/dba/blog.txt
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: '0655'
      when: ansible_nodename == "stapp01"

Three of those, differing in the filename and the host in the condition.

Step 2: Checking all three servers first

/opt/dba existed on each one and was empty. Which is what makes the next output worth reading.

Step 3: Running it

TASK [Copy blog.txt file from jump host to App Server 1] ***************
skipping: [stapp02]
skipping: [stapp03]
changed: [stapp01]
PLAY RECAP ***************
stapp01 : ok=2 changed=1 skipped=2
stapp02 : ok=2 changed=1 skipped=2
stapp03 : ok=2 changed=1 skipped=2
  • -rw-r-xr-x 1 tony tony 35 blog.txt
  • -rw-r-xr-x 1 steve steve 27 story.txt
  • -rw-r-xr-x 1 banner banner 22 media.txt

Three different byte counts on three different hosts. Each matches its source exactly, character count with no trailing newline.

That is the strongest single piece of evidence the routing worked, because a condition matching the wrong host would have put the wrong size in the wrong place.

Step 4: The thing I went looking for afterwards

ansible_nodename is not the inventory name. It does not appear on Ansible's special variables page at all, because it is not a magic variable. It is a gathered fact, and in Ansible's fact collection code it is set directly from Python:

platform_facts['nodename'] = platform.node()

So it is what the target machine calls itself, read off the target after setup runs. inventory_hostname, which yesterday's template used, is documented as "The inventory name for the 'current' host being iterated over in the play", and the controller knows it before contacting anything.

Here they agree, because the inventory line is stapp01 ansible_host=stapp01 and the machine's hostname is also stapp01. Nothing requires that. The entire point of ansible_host= is to let an inventory alias differ from the thing it points at, and real inventories are full of names like web1 and db-primary on machines whose hostname is something else.

Step 5: What happens if they disagree

Every condition is false on every host. All three tasks skip everywhere. The recap reads:

stapp01 : ok=1 changed=0 skipped=3 failed=0

No error, no warning, failed=0. A playbook that copied nothing reports a clean run. The only signal is a changed=0 that somebody has to notice and interpret.

A when has no concept of "should have matched something". There is nothing in Ansible that fails a play because a condition was never true anywhere. So the number to read in this playbook is skipped. Mine was 2 per host, meaning exactly one task ran on each. Nine would have meant the conditions matched nobody.

What the docs recommend

The one-word fix is to use the variable that means what the task means:

when: inventory_hostname == "stapp01"

That also makes gather_facts: no possible. As written, the play gathers facts on three servers purely to read back a name the inventory already knew, and fact gathering is the slowest step in a play this small.

The better shape drops the conditionals, because three near-identical tasks differing in one value are a loop wearing a disguise:

vars:
  file_for:
    stapp01: blog.txt
    stapp02: story.txt
    stapp03: media.txt
tasks:
  - name: Copy this host's file from the jump host
    copy:
      src: "/usr/src/dba/{{ file_for[inventory_hostname] }}"
      dest: "/opt/dba/{{ file_for[inventory_hostname] }}"
      owner: "{{ ansible_user }}"
      group: "{{ ansible_user }}"
      mode: '0655'

One task instead of three. A host missing from the dictionary fails loudly with an undefined-key error instead of skipping quietly, which inverts the failure mode, and that is the whole argument.

The original runs nine task-host evaluations to perform three copies. The task asked for conditionals, so the playbook uses them. Knowing what they cost is a separate thing from knowing how to write them.

One small note on the result: /opt/dba is still owned by root on all three servers. The tasks set ownership on the files and never touch the directory, so tony owns blog.txt and cannot create a second file next to it. copy sets the mode of what it writes, not of the path it writes into.

Task 2: An Application Gateway in front of a VM

An NSG with an HTTP rule, a VM running nginx from user data, and a gateway with four named sub-resources.

Step 1: The CLI could not send the only allowed value

RequestDisallowedByPolicy: Only the Basic SKU is allowed for Azure Application Gateway.

--sku: Allowed values: Standard_Medium, Standard_Small, Standard_v2, WAF_Large, WAF_Medium, WAF_v2. Six values the CLI can emit, one the subscription accepts, no overlap.

Not permissions, not quota, not fixable with a flag. A CLI enum can be narrower than the API behind it. That list is hard-coded in the command definition, and Basic became generally available after it was written. The REST API takes the value; the CLI will not send it.

Checking --help cost two seconds, and it is worth doing whenever something is rejected without a round trip to Azure, because a client-side enum error and a server-side rejection look identical in a terminal and have nothing in common.

Step 2: The constraint turned out to be a better route

az network application-gateway create cannot name its own sub-resources. It always produces appGatewayBackendPool, appGatewayHttpListener and rule1. This task names four of them. Doing that through the CLI means nine separate writes, each a full PUT of one to three minutes, on top of a fifteen-minute create. Deleting the default rule first does not help, because a gateway with zero routing rules fails validation.

An ARM template did all of it in one deployment, because it declares the final state instead of mutating toward it. The sub-resources reference each other by composed ID:

"variables": {
  "agwId": "[resourceId('Microsoft.Network/applicationGateways','nautilus-agw')]"
},
"frontendPort": {
  "id": "[concat(variables('agwId'),'/frontendPorts/port_80')]"
}

resourceId() builds an ID from names without the resource existing, which is what makes a self-referential template legal.

Two gates in front of the deploy, both returning in seconds:

python3 -m json.tool /tmp/agw.json > /dev/null
az deployment group validate -g "$RG" --template-file /tmp/agw.json --parameters vmPrivateIp="$VMIP"

The second earned its place. validate runs schema checks, reference resolution and policy evaluation server-side, so Basic was confirmed acceptable before anything was built. Finding a rejected SKU after a fifteen-minute wait on a one-hour lab clock is a different afternoon.

Step 3: Something deleted my NSG rule

The NSG and its rule went in first, successfully. After az vm create ... --nsg nautilus-nsg, the NSG held one rule, and not the one I had put there:

[
  {
    "name": "default-allow-ssh",
    "dport": "22",
    "pri": 1000
  }
]

Allow-HTTP was gone, so port 80 fell through to DenyAllInBound. The documentation describes --nsg as "the name to use when creating a new Network Security Group (default) or referencing an existing one", which reads as reuse. What I observed is that the NSG ended up holding only the SSH rule az vm create adds by default. It is a write, not a reference.

That puts it in a family I keep running into, as the worst member so far.

  • az resource tag replaces all tags.
  • management-policy create replaces all lifecycle rules.
  • set-policy --key-permissions replaces that category.

All three replace something you were explicitly setting. This one replaces a resource you only mentioned in passing, while creating something else.

What the docs recommend

The diagnostic I ran during that fault returned an empty array, and I nearly believed it.

--query "value[].securityRules[]..." # []
--query "value[].effectiveSecurityRules[]..." # the rules

az network nic list-effective-nsg puts them under effectiveSecurityRules. securityRules does not exist on that object. Same mistake as yesterday's properties.leaseState, and worse here because of when it happened. [] reads as "the NSG has no rules", which was accidentally adjacent to the truth. A plausible wrong answer ends an investigation. An obviously wrong one does not.

The fix is two lines and no guessing:

az network nic list-effective-nsg --ids "$NICID" -o json \
  | python3 -c "import sys,json;d=json.load(sys.stdin);print(list(d['value'][0].keys()))"
[ 'association' , 'effectiveSecurityRules' , 'networkSecurityGroup' , 'tagMap' ]

And a correction to something I wrote in an earlier note. I had recorded that both v2 and Basic gateways need inbound from the GatewayManager service tag on ports 65200 to 65535. The documentation gives two ranges and does not mention Basic at all: 65200-65535 for v2, 65503-65534 for v1. What it does say is the general rule that the range "differs based on SKU and is required for communicating the status of the backend health".

Leaving the gateway subnet without an NSG, which is what I did, sidesteps the question entirely and remains the right call. Two more things from that page worth carrying: platform health monitoring uses TCP 65502 and 54321 and UDP 12345, separately from the GatewayManager range, and the gateway subnet is exclusive, so you cannot put anything else in it.

What I learned

  • ansible_nodename is a gathered fact set from platform.node(), the target's own name. inventory_hostname is the inventory's name for it. Not the same variable, and not required to agree.
  • A when that is false everywhere skips every task and reports failed=0. Read skipped, not just changed.
  • Three near-identical tasks differing by one value are a loop. A dictionary keyed by host fails loudly on a missing key instead of skipping quietly.
  • copy sets the mode of the file it writes, not of the directory it writes into.
  • A CLI enum can be narrower than the API behind it, and policy can require a value the CLI will not send.
  • az vm create --nsg <name> writes that NSG rather than referencing it, and replaces its rule set.
  • Print a response's top-level keys before writing a query against it, especially during a diagnosis.

So here is the Day 93 question. When your automation does nothing at all, what does it print? Mine prints a clean recap with failed=0, and I would have to be paying attention to the one number that changed to notice.

Day 93 down. Seven to go.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.