Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numeric month to string month name in Ansible

I would like to convert the numeric representation of a month to its name. I would like to do this in a Jinja template, using Ansible.

E.g.:

  • when given 1 the output should be Jan
  • when given 2 the output should be Feb
  • etc.

Here is my template tentative at achieving this:

m_usg_month: "{{data.month | to_datetime('%b')}}"

But, this gives me the error:

fatal: [localhost]: FAILED! => {"changed": false, "msg": "ValueError: time data '1' does not match format '%b'"}

Input

data:
  month: "1"

Expected Output

m_usg_month: "Jan"
like image 598
Vinny Avatar asked Nov 26 '25 03:11

Vinny


1 Answers

Your issue is coming from the fact that you are providing your desired output format to the filter to_datetime, while what you actually need to do is to pass the input format.

Then, use the strftime method on the resulting datetime, with your desired output format, this time.

So:

- debug:
    msg: "{{ (data.month | string | to_datetime('%m')).strftime('%b') }}"

As a full-fledged example:

- debug:
    msg: "{{ (data.month | string | to_datetime('%m')).strftime('%b') }}"
  loop: "{{ range(1, 13) }}"
  vars:
    data:
      month: "{{ item }}"

Would yield:

TASK [debug] *************************************************************
ok: [localhost] => (item=1) => 
  msg: Jan
ok: [localhost] => (item=2) => 
  msg: Feb
ok: [localhost] => (item=3) => 
  msg: Mar
ok: [localhost] => (item=4) => 
  msg: Apr
ok: [localhost] => (item=5) => 
  msg: May
ok: [localhost] => (item=6) => 
  msg: Jun
ok: [localhost] => (item=7) => 
  msg: Jul
ok: [localhost] => (item=8) => 
  msg: Aug
ok: [localhost] => (item=9) => 
  msg: Sep
ok: [localhost] => (item=10) => 
  msg: Oct
ok: [localhost] => (item=11) => 
  msg: Nov
ok: [localhost] => (item=12) => 
  msg: Dec
like image 56
β.εηοιτ.βε Avatar answered Nov 28 '25 15:11

β.εηοιτ.βε