Search code examples
ansiblejinja2ansible-2.x

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"

Solution

  • 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