Mohamed Behairy
Mohamed Behairy

Reputation: 21

Delete blocks in YAML file using Python

I have a YAML file that contains a Jenkins configuration as below:

credentials:
  system:
    domainCredentials:
    - credentials:
      - usernamePassword:
          description: "github"
          id: "github"
          password: "{AQAAABAAAAAwHFhIFIYeda2gWu9qfLX8fRAOlQjdb+Eyo3K9EoYSCxT6nrTLt+QRKSBo4Sx4qOXH1Lfn2EjfAQfklR63XqWZAw==}"
          scope: GLOBAL
          username: "admin"
      - string:
          description: "test"
          id: "test"
          scope: GLOBAL
          secret: "{AQAAABAAAAAQyWoMCVDAldVDxS1J15gLzqTvo2Dr6j3ckrdX3C1/3sg=}"
jenkins:
  agentProtocols:
  - "JNLP4-connect"
  - "Ping"
  authorizationStrategy:
    loggedInUsersCanDoAnything:
      allowAnonymousRead: false
  crumbIssuer:
    standard:
      excludeClientIPFromCrumb: false
  disableRememberMe: false
  labelAtoms:
  - name: "master"
  markupFormatter: "plainText"
  mode: NORMAL
  myViewsTabBar: "standard"
  numExecutors: 2
  primaryView:
    all:
      name: "all"
  projectNamingStrategy: "standard"
  quietPeriod: 5
  remotingSecurity:
    enabled: true
  scmCheckoutRetryCount: 0
  securityRealm:
    local:
      allowsSignup: false
      enableCaptcha: false
      users:
      - id: "admin"
        name: "admin"
        properties:
        - "myView"
        - preferredProvider:
            providerId: "default"
        - "timezone"
        - mailer:
            emailAddress: "[email protected]"
        - "apiToken"
  slaveAgentPort: 50000
  updateCenter:
    sites:
    - id: "default"
      url: "https://updates.jenkins.io/update-center.json"
  views:
  - all:
      name: "all"
  viewsTabBar: "standard"
security:
  apiToken:
    creationOfLegacyTokenEnabled: false
    tokenGenerationOnCreationEnabled: false
    usageStatisticsEnabled: true
  sSHD:
    port: -1
unclassified:
  artifactoryBuilder:
    jfrogPipelinesServer:
      bypassProxy: false
      connectionRetries: 3
      credentialsConfig:
        overridingCredentials: false
        username: "****"
      timeout: 300
    useCredentialsPlugin: false
  buildDiscarders:
    configuredBuildDiscarders:
    - "jobBuildDiscarder"
  buildStepOperation:
    enabled: false
  email-ext:
    adminRequiredForTemplateTesting: false
    allowUnregisteredEnabled: false
    charset: "UTF-8"
    debugMode: false
    defaultBody: |-
      $PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:

      Check console output at $BUILD_URL to view the results.
    defaultSubject: "$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!"
    defaultTriggerIds:
    - "hudson.plugins.emailext.plugins.trigger.FailureTrigger"
    maxAttachmentSize: -1
    maxAttachmentSizeMb: -1
    precedenceBulk: false
    watchingEnabled: false
  fingerprints:
    fingerprintCleanupDisabled: false
    storage: "file"
  gitHubConfiguration:
    apiRateLimitChecker: ThrottleForNormalize
  gitHubPluginConfig:
    hookUrl: "http://localhost:8080/github-webhook/"
  gitSCM:
    addGitTagAction: false
    allowSecondFetch: false
    createAccountBasedOnEmail: false
    disableGitToolChooser: false
    hideCredentials: false
    showEntireCommitSummaryInChanges: false
    useExistingAccountWithSameEmail: false
  ivyBuildTrigger:
    extendedVersionMatching: false
  junitTestResultStorage:
    storage: "file"
  location:
    adminAddress: "address not configured yet <nobody@nowhere>"
    url: "http://localhost:8080/"
  mailer:
    charset: "UTF-8"
    useSsl: false
    useTls: false
  mavenModuleSet:
    localRepository: "default"
  pollSCM:
    pollingThreadCount: 10
  timestamper:
    allPipelines: false
    elapsedTimeFormat: "'<b>'HH:mm:ss.S'</b> '"
    systemTimeFormat: "'<b>'HH:mm:ss'</b> '"
tool:
  git:
    installations:
    - home: "git"
      name: "Default"
  mavenGlobalConfig:
    globalSettingsProvider: "standard"
    settingsProvider: "standard"

I need to delete two blocks "unclassified:" and "location:", how can I do that using Python?

Upvotes: 2

Views: 2013

Answers (1)

ccre
ccre

Reputation: 422

You can use pyyaml module to do this. Here's an example:

import yaml

with open('file.yaml', 'r') as file:
    data = yaml.safe_load(file)
data.pop('unclassified')
with open('file.yaml', 'w') as file:
    yaml.safe_dump(data, file)

Upvotes: 2

Related Questions