github.com/djenriquez/nomad-1@v0.8.1/command/job_init.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"strings"
     8  )
     9  
    10  const (
    11  	// DefaultInitName is the default name we use when
    12  	// initializing the example file
    13  	DefaultInitName = "example.nomad"
    14  )
    15  
    16  // JobInitCommand generates a new job template that you can customize to your
    17  // liking, like vagrant init
    18  type JobInitCommand struct {
    19  	Meta
    20  }
    21  
    22  func (c *JobInitCommand) Help() string {
    23  	helpText := `
    24  Usage: nomad job init
    25  Alias: nomad init
    26  
    27    Creates an example job file that can be used as a starting
    28    point to customize further.
    29  `
    30  	return strings.TrimSpace(helpText)
    31  }
    32  
    33  func (c *JobInitCommand) Synopsis() string {
    34  	return "Create an example job file"
    35  }
    36  
    37  func (c *JobInitCommand) Run(args []string) int {
    38  	// Check for misuse
    39  	if len(args) != 0 {
    40  		c.Ui.Error(c.Help())
    41  		return 1
    42  	}
    43  
    44  	// Check if the file already exists
    45  	_, err := os.Stat(DefaultInitName)
    46  	if err != nil && !os.IsNotExist(err) {
    47  		c.Ui.Error(fmt.Sprintf("Failed to stat '%s': %v", DefaultInitName, err))
    48  		return 1
    49  	}
    50  	if !os.IsNotExist(err) {
    51  		c.Ui.Error(fmt.Sprintf("Job '%s' already exists", DefaultInitName))
    52  		return 1
    53  	}
    54  
    55  	// Write out the example
    56  	err = ioutil.WriteFile(DefaultInitName, []byte(defaultJob), 0660)
    57  	if err != nil {
    58  		c.Ui.Error(fmt.Sprintf("Failed to write '%s': %v", DefaultInitName, err))
    59  		return 1
    60  	}
    61  
    62  	// Success
    63  	c.Ui.Output(fmt.Sprintf("Example job file written to %s", DefaultInitName))
    64  	return 0
    65  }
    66  
    67  var defaultJob = strings.TrimSpace(`
    68  # There can only be a single job definition per file. This job is named
    69  # "example" so it will create a job with the ID and Name "example".
    70  
    71  # The "job" stanza is the top-most configuration option in the job
    72  # specification. A job is a declarative specification of tasks that Nomad
    73  # should run. Jobs have a globally unique name, one or many task groups, which
    74  # are themselves collections of one or many tasks.
    75  #
    76  # For more information and examples on the "job" stanza, please see
    77  # the online documentation at:
    78  #
    79  #     https://www.nomadproject.io/docs/job-specification/job.html
    80  #
    81  job "example" {
    82    # The "region" parameter specifies the region in which to execute the job. If
    83    # omitted, this inherits the default region name of "global".
    84    # region = "global"
    85  
    86    # The "datacenters" parameter specifies the list of datacenters which should
    87    # be considered when placing this task. This must be provided.
    88    datacenters = ["dc1"]
    89  
    90    # The "type" parameter controls the type of job, which impacts the scheduler's
    91    # decision on placement. This configuration is optional and defaults to
    92    # "service". For a full list of job types and their differences, please see
    93    # the online documentation.
    94    #
    95    # For more information, please see the online documentation at:
    96    #
    97    #     https://www.nomadproject.io/docs/jobspec/schedulers.html
    98    #
    99    type = "service"
   100  
   101    # The "constraint" stanza defines additional constraints for placing this job,
   102    # in addition to any resource or driver constraints. This stanza may be placed
   103    # at the "job", "group", or "task" level, and supports variable interpolation.
   104    #
   105    # For more information and examples on the "constraint" stanza, please see
   106    # the online documentation at:
   107    #
   108    #     https://www.nomadproject.io/docs/job-specification/constraint.html
   109    #
   110    # constraint {
   111    #   attribute = "${attr.kernel.name}"
   112    #   value     = "linux"
   113    # }
   114  
   115    # The "update" stanza specifies the update strategy of task groups. The update
   116    # strategy is used to control things like rolling upgrades, canaries, and
   117    # blue/green deployments. If omitted, no update strategy is enforced. The
   118    # "update" stanza may be placed at the job or task group. When placed at the
   119    # job, it applies to all groups within the job. When placed at both the job and
   120    # group level, the stanzas are merged with the group's taking precedence.
   121    #
   122    # For more information and examples on the "update" stanza, please see
   123    # the online documentation at:
   124    #
   125    #     https://www.nomadproject.io/docs/job-specification/update.html
   126    #
   127    update {
   128      # The "max_parallel" parameter specifies the maximum number of updates to
   129      # perform in parallel. In this case, this specifies to update a single task
   130      # at a time.
   131      max_parallel = 1
   132      
   133      # The "min_healthy_time" parameter specifies the minimum time the allocation
   134      # must be in the healthy state before it is marked as healthy and unblocks
   135      # further allocations from being updated.
   136      min_healthy_time = "10s"
   137      
   138      # The "healthy_deadline" parameter specifies the deadline in which the
   139      # allocation must be marked as healthy after which the allocation is
   140      # automatically transitioned to unhealthy. Transitioning to unhealthy will
   141      # fail the deployment and potentially roll back the job if "auto_revert" is
   142      # set to true.
   143      healthy_deadline = "3m"
   144      
   145      # The "auto_revert" parameter specifies if the job should auto-revert to the
   146      # last stable job on deployment failure. A job is marked as stable if all the
   147      # allocations as part of its deployment were marked healthy.
   148      auto_revert = false
   149      
   150      # The "canary" parameter specifies that changes to the job that would result
   151      # in destructive updates should create the specified number of canaries
   152      # without stopping any previous allocations. Once the operator determines the
   153      # canaries are healthy, they can be promoted which unblocks a rolling update
   154      # of the remaining allocations at a rate of "max_parallel".
   155      #
   156      # Further, setting "canary" equal to the count of the task group allows
   157      # blue/green deployments. When the job is updated, a full set of the new
   158      # version is deployed and upon promotion the old version is stopped.
   159      canary = 0
   160    }
   161  
   162    # The migrate stanza specifies the group's strategy for migrating off of
   163    # draining nodes. If omitted, a default migration strategy is applied.
   164    #
   165    # For more information on the "migrate" stanza, please see 
   166    # the online documentation at:
   167    #
   168    #     https://www.nomadproject.io/docs/job-specification/migrate.html
   169    #
   170    migrate {
   171      # Specifies the number of task groups that can be migrated at the same
   172      # time. This number must be less than the total count for the group as
   173      # (count - max_parallel) will be left running during migrations.
   174      max_parallel = 1
   175  
   176      # Specifies the mechanism in which allocations health is determined. The
   177      # potential values are "checks" or "task_states".
   178      health_check = "checks"
   179  
   180      # Specifies the minimum time the allocation must be in the healthy state
   181      # before it is marked as healthy and unblocks further allocations from being
   182      # migrated. This is specified using a label suffix like "30s" or "15m".
   183      min_healthy_time = "10s"
   184  
   185      # Specifies the deadline in which the allocation must be marked as healthy
   186      # after which the allocation is automatically transitioned to unhealthy. This
   187      # is specified using a label suffix like "2m" or "1h".
   188      healthy_deadline = "5m"
   189    }
   190  
   191    # The "group" stanza defines a series of tasks that should be co-located on
   192    # the same Nomad client. Any task within a group will be placed on the same
   193    # client.
   194    #
   195    # For more information and examples on the "group" stanza, please see
   196    # the online documentation at:
   197    #
   198    #     https://www.nomadproject.io/docs/job-specification/group.html
   199    #
   200    group "cache" {
   201      # The "count" parameter specifies the number of the task groups that should
   202      # be running under this group. This value must be non-negative and defaults
   203      # to 1.
   204      count = 1
   205  
   206      # The "restart" stanza configures a group's behavior on task failure. If
   207      # left unspecified, a default restart policy is used based on the job type.
   208      #
   209      # For more information and examples on the "restart" stanza, please see
   210      # the online documentation at:
   211      #
   212      #     https://www.nomadproject.io/docs/job-specification/restart.html
   213      #
   214      restart {
   215        # The number of attempts to run the job within the specified interval.
   216        attempts = 2
   217        interval = "30m"
   218  
   219        # The "delay" parameter specifies the duration to wait before restarting
   220        # a task after it has failed.
   221        delay = "15s"
   222  
   223       # The "mode" parameter controls what happens when a task has restarted
   224       # "attempts" times within the interval. "delay" mode delays the next
   225       # restart until the next interval. "fail" mode does not restart the task
   226       # if "attempts" has been hit within the interval.
   227        mode = "fail"
   228      }
   229  
   230      # The "ephemeral_disk" stanza instructs Nomad to utilize an ephemeral disk
   231      # instead of a hard disk requirement. Clients using this stanza should
   232      # not specify disk requirements in the resources stanza of the task. All
   233      # tasks in this group will share the same ephemeral disk.
   234      #
   235      # For more information and examples on the "ephemeral_disk" stanza, please
   236      # see the online documentation at:
   237      #
   238      #     https://www.nomadproject.io/docs/job-specification/ephemeral_disk.html
   239      #
   240      ephemeral_disk {
   241        # When sticky is true and the task group is updated, the scheduler
   242        # will prefer to place the updated allocation on the same node and
   243        # will migrate the data. This is useful for tasks that store data
   244        # that should persist across allocation updates.
   245        # sticky = true
   246        # 
   247        # Setting migrate to true results in the allocation directory of a
   248        # sticky allocation directory to be migrated.
   249        # migrate = true
   250  
   251        # The "size" parameter specifies the size in MB of shared ephemeral disk
   252        # between tasks in the group.
   253        size = 300
   254      }
   255  
   256      # The "task" stanza creates an individual unit of work, such as a Docker
   257      # container, web application, or batch processing.
   258      #
   259      # For more information and examples on the "task" stanza, please see
   260      # the online documentation at:
   261      #
   262      #     https://www.nomadproject.io/docs/job-specification/task.html
   263      #
   264      task "redis" {
   265        # The "driver" parameter specifies the task driver that should be used to
   266        # run the task.
   267        driver = "docker"
   268  
   269        # The "config" stanza specifies the driver configuration, which is passed
   270        # directly to the driver to start the task. The details of configurations
   271        # are specific to each driver, so please see specific driver
   272        # documentation for more information.
   273        config {
   274          image = "redis:3.2"
   275          port_map {
   276            db = 6379
   277          }
   278        }
   279  
   280        # The "artifact" stanza instructs Nomad to download an artifact from a
   281        # remote source prior to starting the task. This provides a convenient
   282        # mechanism for downloading configuration files or data needed to run the
   283        # task. It is possible to specify the "artifact" stanza multiple times to
   284        # download multiple artifacts.
   285        #
   286        # For more information and examples on the "artifact" stanza, please see
   287        # the online documentation at:
   288        #
   289        #     https://www.nomadproject.io/docs/job-specification/artifact.html
   290        #
   291        # artifact {
   292        #   source = "http://foo.com/artifact.tar.gz"
   293        #   options {
   294        #     checksum = "md5:c4aa853ad2215426eb7d70a21922e794"
   295        #   }
   296        # }
   297  
   298        # The "logs" stanza instructs the Nomad client on how many log files and
   299        # the maximum size of those logs files to retain. Logging is enabled by
   300        # default, but the "logs" stanza allows for finer-grained control over
   301        # the log rotation and storage configuration.
   302        #
   303        # For more information and examples on the "logs" stanza, please see
   304        # the online documentation at:
   305        #
   306        #     https://www.nomadproject.io/docs/job-specification/logs.html
   307        #
   308        # logs {
   309        #   max_files     = 10
   310        #   max_file_size = 15
   311        # }
   312  
   313        # The "resources" stanza describes the requirements a task needs to
   314        # execute. Resource requirements include memory, network, cpu, and more.
   315        # This ensures the task will execute on a machine that contains enough
   316        # resource capacity.
   317        #
   318        # For more information and examples on the "resources" stanza, please see
   319        # the online documentation at:
   320        #
   321        #     https://www.nomadproject.io/docs/job-specification/resources.html
   322        #
   323        resources {
   324          cpu    = 500 # 500 MHz
   325          memory = 256 # 256MB
   326          network {
   327            mbits = 10
   328            port "db" {}
   329          }
   330        }
   331  
   332        # The "service" stanza instructs Nomad to register this task as a service
   333        # in the service discovery engine, which is currently Consul. This will
   334        # make the service addressable after Nomad has placed it on a host and
   335        # port.
   336        #
   337        # For more information and examples on the "service" stanza, please see
   338        # the online documentation at:
   339        #
   340        #     https://www.nomadproject.io/docs/job-specification/service.html
   341        #
   342        service {
   343          name = "redis-cache"
   344          tags = ["global", "cache"]
   345          port = "db"
   346          check {
   347            name     = "alive"
   348            type     = "tcp"
   349            interval = "10s"
   350            timeout  = "2s"
   351          }
   352        }
   353  
   354        # The "template" stanza instructs Nomad to manage a template, such as
   355        # a configuration file or script. This template can optionally pull data
   356        # from Consul or Vault to populate runtime configuration data.
   357        #
   358        # For more information and examples on the "template" stanza, please see
   359        # the online documentation at:
   360        #
   361        #     https://www.nomadproject.io/docs/job-specification/template.html
   362        #
   363        # template {
   364        #   data          = "---\nkey: {{ key \"service/my-key\" }}"
   365        #   destination   = "local/file.yml"
   366        #   change_mode   = "signal"
   367        #   change_signal = "SIGHUP"
   368        # }
   369  
   370        # The "template" stanza can also be used to create environment variables
   371        # for tasks that prefer those to config files. The task will be restarted
   372        # when data pulled from Consul or Vault changes.
   373        #
   374        # template {
   375        #   data        = "KEY={{ key \"service/my-key\" }}"
   376        #   destination = "local/file.env"
   377        #   env         = true
   378        # }
   379  
   380        # The "vault" stanza instructs the Nomad client to acquire a token from
   381        # a HashiCorp Vault server. The Nomad servers must be configured and
   382        # authorized to communicate with Vault. By default, Nomad will inject
   383        # The token into the job via an environment variable and make the token
   384        # available to the "template" stanza. The Nomad client handles the renewal
   385        # and revocation of the Vault token.
   386        #
   387        # For more information and examples on the "vault" stanza, please see
   388        # the online documentation at:
   389        #
   390        #     https://www.nomadproject.io/docs/job-specification/vault.html
   391        #
   392        # vault {
   393        #   policies      = ["cdn", "frontend"]
   394        #   change_mode   = "signal"
   395        #   change_signal = "SIGHUP"
   396        # }
   397  
   398        # Controls the timeout between signalling a task it will be killed
   399        # and killing the task. If not set a default is used.
   400        # kill_timeout = "20s"
   401      }
   402    }
   403  }
   404  `)