2

I am trying to replace a value for key ipAddress using sed for the below yaml block:

networkInterfaces:
- network:
    id: network-1111   
    ipAddress: 192.168.0.0

The command I tried: sed -i 's/\(.*ipAddress:.*\)/ipAddress: 192.168.0.1/g' filename.yaml

This actually replaced the text, but it didn't nest the key under networkInterfaces; instead, it placed it in the main block.

Output after SED

networkInterfaces:
  - network:
      id: network-1834
ipAddress: 192.168.0.1

I tried yq

yq -i '.networkInterfaces.ipAddress = "192.168.0.0"' filename.yaml

... that resulted in an error:

cannot index array with 'ipAddress' (strconv.ParseInt: parsing "ipAddress": invalid syntax)

I'm looking to replace the value for ipAddress.

1
  • FYI the reason why the key didn't remain nested with sed in this case is because you consumed the leading whitespace as you used .* before the key but then you replaced with string of ip.... If you remove the leading .* it does work as intended. Commented Aug 12, 2024 at 0:45

1 Answer 1

3

This answer assumes that you are using Mike Farah's yq utility (which you are, according to the error message you are showing). Andrey Kislyuk's yq is slightly different.


networkInterfaces is a list, so you can't access network or ipAddress beneath it without picking what list element to access these in.

If you only have the single element, you could use

yq '.networkInterfaces[0].network.ipAddress = "192.168.0.1"' file

That is, set the ipAddress of the network of the first element of the networkInterfaces list to the string 192.168.0.1.

To set the ipAddress of an entry with a particular id:

yq '.networkInterfaces[] |= select(.network.id == "network-1111").network.ipAddress = "192.168.0.1"' file

To use shell variables to hold the query id and the new IP number:

id=network-1111 newip=192.168.0.1 yq '.networkInterfaces[] |= select(.network.id == env(id)).network.ipAddress = env(newip)' file
1
  • Although this solution works, note that yq may remove blank lines as well as remove line breaks in multi-line text scalars in the YAML file it writes. The former issue has a few work-arounds, but the latter left me stuck without any good work-arounds (back to sed, I guess)? Commented Jun 24, 2024 at 13:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.