Priya
Priya

Reputation: 303

Replace values in yml file with Shell variable

I have a config.yml file like this:

INVOCATION_VARIABLES:
  deployTarget1:
    cpspgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP1'
      HA_PGPOOL_WATCHDOG_PORT: '5445'
      PCP_PORT: '5440'
      PGPOOL_PORT: '5441'
      POOL_NUMBER: '0'
    pgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP2'
      HA_PGPOOL_WATCHDOG_PORT: '5435'
      PCP_PORT: '5430'
      PGPOOL_PORT: '5431'
      POOL_NUMBER: '0'
  deployTarget2:
    cpspgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP1'
      HA_PGPOOL_WATCHDOG_PORT: '5445'
      PCP_PORT: '5440'
      PGPOOL_PORT: '5441'
      POOL_NUMBER: '1'
    pgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP2'
      HA_PGPOOL_WATCHDOG_PORT: '5435'
      PCP_PORT: '5430'
      PGPOOL_PORT: '5431'
      POOL_NUMBER: '1'
  deployTarget3:
    cpspgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP1'
      HA_PGPOOL_WATCHDOG_PORT: '5445'
      PCP_PORT: '5440'
      PGPOOL_PORT: '5441'
      POOL_NUMBER: '2'
    pgpoolc:
    - HA_PGPOOL_VIRTUAL_IP: 'vIP2'
      HA_PGPOOL_WATCHDOG_PORT: '5435'
      PCP_PORT: '5430'
      PGPOOL_PORT: '5431'
      POOL_NUMBER: '2'

I have created a shell script which will give me the values of virtualIP1='10.104.84.221' and virtualIP2='10.104.94.2'. How can I make the shell script replace all vIP1 values with virtualIP1 and vIP2 with virtualIP2 in shell script?

Upvotes: 0

Views: 4324

Answers (3)

tshiono
tshiono

Reputation: 22087

If yq is your option, please try the following:

export virtualIP1='10.104.84.221'
export virtualIP2='10.104.94.2'

yq -y < config.yml '(.. | select(.HA_PGPOOL_VIRTUAL_IP? == "vIP1") | .HA_PGPOOL_VIRTUAL_IP) |= env.virtualIP1 | (.. | select(.HA_PGPOOL_VIRTUAL_IP? == "vIP2") | .HA_PGPOOL_VIRTUAL_IP) |= env.virtualIP2'

Upvotes: 1

Hasan Rumman
Hasan Rumman

Reputation: 597

  1. Initialise virtualIP1 and virtualIP2

    virtualIP1='10.104.84.221'

    virtualIP2='10.104.94.2'

  2. Run below to see if you get the desired output:

    sed -e "s/vIP1/$virtualIP1/g" filename

    sed -e "s/vIP2/$virtualIP2/g" filename

  3. If above gives you the desired output, then run sed with i instead of e option, preferably keeping backup of old file.

    sed -i.bak "s/vIP1/$virtualIP1/g" filename

    sed -i.bak "s/vIP2/$virtualIP2/g" filename

Upvotes: 1

UtLox
UtLox

Reputation: 4164

You can try this:

sed -e 's/vIP1/10.104.84.221/' -e 's/vIP2/10.104.94.2/' config.yml

Upvotes: 0

Related Questions